devise介绍+使用
1:Gemfile中加入: gem 'devise'
2:建立devise档案: rails g devise:install(自动在routes.rb中加入:devise_for:user)
3:预设定网站网址:在config/environmentents/development.rb与production.rb中加入
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
4:在app/views/layouts/application.html.erb layout中加入:(提示flash信息)
<p style="line-height: 18px; font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace; background-color: #fafafa;">? <p style="line-height: 18px; font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace; background-color: #fafafa;">5:设定主页,在routes.rb中
root :to => ""
6:产生User model以及Migration
rails ?g devise user
7:如果需要E-mail验证登录功能,修改user.rb migration将confirmable打开
8:产生view模板
rails g devise:views
9:建立资料表
rake db:migration
使用:
在需要登录的control中加上:before_filter:authenticate_user!
!!
定制登录信息:(注意修改:)
devise默认是email和密码登录,那么,现在用用户名登录!配置如下:
1:添加username字段到User表单
rails?generate?migration?add_username_to_users?username:string?
rake db:migration
2:修改配置文件:是devise默认用username登录/config/initializers/devise.rb
config.authentication_keys?=?[?:username?]
config.sign_out_via = :get
3:修改注册页面,app\views\devise\registrations\new.html.erb(类似修改其他devise的视图)
<h2>Sign up</h2>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
? <%= devise_error_messages! %>
? <p><%= f.label :username %><br />//////
? <%= f.text_field :username %></p>//////
? <p><%= f.label :email %><br />
? <%= f.email_field :email %></p>
? <p><%= f.label :password %><br />
? <%= f.password_field :password %></p>
? <p><%= f.label :password_confirmation %><br />
? <%= f.password_field :password_confirmation %></p>
? <p><%= f.submit "Sign up" %></p>
<% end %>
<%= render :partial => "devise/shared/links" %>
4:在需要登入的 controller 加上before_filter :authenticate_user!
?
5:可以在 Layout 中加上登入登出選單
?
<% if current_user %> <%= link_to('登出', destroy_user_session_path, :method => :delete) %> | <%= link_to('修改密碼', edit_registration_path(:user)) %> <% else %> <%= link_to('註冊', new_registration_path(:user)) %> | <%= link_to('登入', new_session_path(:user)) %> <% end %>