github: https://github.com/plataformatec/devise
http://www.haojii.com/category/ruby-on-rails/
昨天对rails的devise略做了点研究,以下是一点总结
Devise源于Warden,而warden是一个基于Rack的验证权限gem,不过,使用devise实际并不需要任何关于warden的知识
进入项目
1、添加gem
gem 'devise'
2、更新本地gem
bundle install
3、创建页面
rails g controller home index
4、初始化devise
rails g devise:install
会有如下提示:
-
1. Setup default url options for your specific environment. Here is an
example of development environment:
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
This is a required Rails configuration. In production it must be 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. If you are deploying Rails 3.1 on Heroku, you may want to set:
config.assets.initialize_on_precompile = false
On config/application.rb forcing your application to not access the DB
or load models when precompiling your assets.
进行相关配置
5、与模型User关联
rails g devise User
这条命令会生成一个user.rb model文件,一个migration文件和一个devise_for的路由
我们可以看到User model和普通的ActiveRecord的区别并不大,主要的差别是调用了devise方法,当然这也是配置的关键。Devise方法有很多的参数用来标识是否使用对应的功能模块
Devise参数?(还不了解)
6.执行迁移任务
rake db:migrate
查看在router.rb文件中的devise_for都产生了什么路由.可以通过rake routes查看
产生了如下路由:登录,登出,重置密码,注册,和修改。如果我们需要,所有这些路由都是可以配置的
7、修改默认访问url
打开routes.rb,加入:root :to => "home#index"
8、修改index.html.erb代码
<% if user_signed_in? -%> <!-- Provided by devise --> <div style="float:right"> <%= current_user.email %> | <%= link_to '用户信息', edit_user_registration_path %> | <%= link_to '退出登录', destroy_user_session_path, :method => :delete %> | </div> <% end -%> <% unless user_signed_in? -%> <div style="float:right"> <%= link_to '注册', new_user_registration_path %> | <%= link_to '登录', new_user_session_path %> </div> <% end -%>
9、启动服务
rails s
10、测试
localhost:3000/home/index