ROR学习笔记(35)——为devise增加新的字段

devise是个很有用的gem。但默认是用email注册和登录的。如果要用增加用户名登录的话,可以如下设置。参考:
http://stackoverflow.com/questions/20126106/devise-error-email-cant-be-blankhttps://github.com/plataformatec/devise#strong-parameters

  1. 增加username字段:
rails g migration add_username_to_user username:string
rake db:migrate
  1. 在/config/initializers/devise.rb中,增加:
config.authentication_keys = [ :username, :email ]
  1. 修改app/views/devise下的相关文件,增加下面代码:
<%= f.label :username %>
<%= f.text_field :username, autofocus: true %>
  1. 在app/controllers/application_controller.rb增加下面代码:
before_action :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
     devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation) }
     devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email, :password, :password_confirmation) }
     devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation) }
  end

这样就可以了还可以参考下面的链接,可以用用户名或者邮箱进行登录
https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address

你可能感兴趣的:(ROR学习笔记(35)——为devise增加新的字段)