本文使用Devise组件生成一个带有登录、注册等基本功能的认证模块。
Ruby版本为 2.2.1
Rails版本为 4.2.3
使用前可以先修改gem sources
言归正传~
1. 新建一个项目,使用mysql数据库
rails new demoDevise -d=mysql
bundle install
rails g devise:install
4. 修改 config/environments/development.rb 或者production.rb,上边加入:
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
devise_for :users
root :to => "welcome#index"
rails g devise user
rake db:migrate
rails g devise:views
8. devise默认使用email字段登录,添加username取代email
rails g migration add_username_to_users
加入代码
add_column :users, :username, :string
rake db:migrate
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protect_from_forgery with: :exception
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :userna me, :password, :password_confirmation) }
devise_parameter_sanitizer.for(:account_update) << :username
end
end
<%= f.label :username %>
<%= f.text_field :username %>
<% if user_signed_in? %>
Welcome <%= current_user.username %>
<%= link_to '退出', destroy_user_session_path, :method => :delete %>
<%= link_to '回到首页', root_path %>
<% else %>
You are not signed in.
<%= link_to 'Login', new_user_session_path %>
<% end %>
<%= notice %>
<%= alert %>
<%= yield %>
<%= render 'layouts/user_widget' %>
config.authentication_keys = [:username]
<%= f.label :username %>
<%= f.text_field :username, autofocus: true %>
<%= f.label :password %>
<%= f.password_field :password, autocomplete: "off" %>