gem devise配置
Step1: Gemfile中加入gem 'devise'
Step3: rails g devise:install
这一步执行完后命令行会提醒要手动进行如下动作:
===============================================================================
Some setup you must do manually if you haven't yet:
1. Ensure you have defined default url options in your environments files. Here
is an example of default_url_options appropriate for a development environment
in config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
In production, :host should be set to the actual host of your application.
2. Ensure you have defined root_url to *something* in your config/routes.rb.
For example:
root to: "home#index"
3. Ensure you have flash messages in app/views/layouts/application.html.erb.
For example:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
4. You can copy Devise views (for customization) to your app by running:
rails g devise:views
Step4: rails g devise User
Step6: rake db:migrate
最后,我们可以看看generator在router.rb文件中的devise_for都产生了什么路由.我们可以通过rake routes,结果如下:
可以把devise的登录页面作为系统首页,设置方式为在routes.rb文件中设置如下信息:
devise_scope :user do
root to: "devise/sessions#new"
end
或者
devise_scope :user do
unauthenticated :user do
root to: "devise/sessions#new",as: :unauthenticated_root #设定登录页为系统默认首页
end
authenticated :user do
root to: "homes#index",as: :authenticated_root #设定系统登录后首页
end
end
application_controlller中加入以下代码
before_action :authenticate_user! #权限控制,管控仅登录用户方可访问login页面以外内容