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下的相关文件,增加下面代码:
<div class="field">
    <%= f.label :username %><br />
    <%= f.text_field :username, autofocus: true %>
  </div>
  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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,009评论 19 139
  • 基本使用在Gemfile里面添加gem 'devise'运行bundle install然后安装devise相关组...
    youngiyang_打码少年阅读 6,287评论 2 11
  • 在Job Listing比赛中自定义过devise界面的栈友想必都看过这篇文章,其中有一项是给注册用户提供了用户名...
    DongHui阅读 1,623评论 0 4
  • 和学生聚会,好幸福
    很显瘦阅读 110评论 0 0
  • 2016.10.27 国检刚结束,今天发生了一件不幸的事,有一个人从我们学校的主楼跳楼了。。忽然间觉得这个社会好可...
    4月的小猴子阅读 407评论 0 0