设计如何在创建用户表单中添加一个addtional字段?

我正在尝试在创建时向我的用户添加用户名。

在设计/注册/新我有:

Sign up

resource_name, :url => registration_path(resource_name)) do |f| %>





"devise/shared/links" %>

问题是没有params[:username]发送到控制器,我在视图中收到以下错误:

 ActiveRecord::StatementInvalid in Devise::RegistrationsController#create Mysql::Error: Column 'username' cannot be null: INSERT INTO `users` (`email`, `encrypted_password`, `reset_password_token`, `reset_password_sent_at`, `remember_created_at`, `sign_in_count`, `current_sign_in_at`, `last_sign_in_at`, `current_sign_in_ip`, `last_sign_in_ip`, `created_at`, `updated_at`, `username`) VALUES ('mail@test.dk', '$2a$10$bWjAXLY8QGXrXeVrGciv2O6mjRF940lajBEsUOPPtPDhKyj0A/gia', NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, '2011-05-15 16:16:36', '2011-05-15 16:16:36', NULL) Rails.root: C:/Rails/densjove Application Trace | Framework Trace | Full Trace Request Parameters: {"utf8"=>"✓", "authenticity_token"=>"qkQ8L0ZonXYxWQ2f4cfdREZ222oa2zGUb/qll3TRxjQ=", "user"=>{"username"=>"hansen", "email"=>"mail@test.dk", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"} 

我已将username coloumn添加到我的模型中,但如何在控制器中访问params[:username]

Rails 4将参数清理移动到控制器。

为设计添加自定义字段的一种方法是在Application Controller中添加一个beforefilter,调用一个方法来定义哪些是允许的参数。

在代码来自https://github.com/plataformatec/devise#strong-parameters

 class ApplicationController < ActionController::Base before_filter :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) << :username end end 

上面的代码是您添加名为username的字段。 如果你要添加first_name,它将是:

 devise_parameter_sanitizer.for(:sign_up) << :first_name 

这是一种方式,我强烈考虑阅读上面链接中的文档,以便了解更多关于自定义设计以允许某些字段的信息。

将用户名字段添加到app / model / user.rb中的attr_accessible

 # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :username 

取自上面的评论#1,以便其他人可以轻松地看到解决方案

Rails 4 Strong Params添加到控制器的方式

https://github.com/plataformatec/devise#strong-parameters

如果您希望在注册用户时添加FirstName,LastName或任何列,则必须使用设计允许的参数配置这些列。

 class ApplicationController < ActionController::Base before_action :configure_new_column_to_devise_permitted_parameters, if: :devise_controller? protected def configure_new_column_to_devise_permitted_parameters registration_params = [:first_name, :last_name, :email, :password, :password_confirmation] if params[:action] == 'create' devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(registration_params) } elsif params[:action] == 'update' devise_parameter_sanitizer.for(:account_update) { |u| u.permit(registration_params << :current_password) } end end end 

例如:要在“用户注册”中添加一个名为alternate_email的列,只需将alternate_email列添加到registration_params

registration_params = [:first_name,:last_name,:email,:password,:password_confirmation,:alternate_email]

电子邮件]