尝试将嵌套的自定义属性Profile(一个Mongoid文档)添加到我的设计用户类.提交Devise注册表单时,它还应创建用户和相应的Profile对象.
我希望最终结果在我的MongoDB中看起来像这样:
用户:
{ # Devise fields: "email": "my@email.com",... # Custom field "profile" : "<object_id>" }
轮廓:
{ "first_name": "Dave",.... }
不幸的是,每当我提交注册时,我都会在控制台中收到此消息.它成功创建了一个用户,但无法创建关联的配置文件.
Started POST "/" for 127.0.0.1 at 2013-04-20 23:37:10 -0400 Processing by Users::RegistrationsController#create as HTML Parameters: {"utf8"=>"✓","authenticity_token"=>"awN2GU8EYEfisU0","user"=> {"profile_attributes"=> {"first_name"=>"Dave","birthday(2i)"=>"4","birthday(3i)"=>"21","birthday(1i)"=>"1933","occupation_title"=>"Software Developer"},"password"=>"[FILTERED]","password_confirmation"=>"[FILTERED]","email"=>"my@email.com"}} Unpermitted parameters: profile_attributes
我有设置:
> Rails 4.0.0beta1,Ruby 2.0.0-p0
> Devise(‘rails4’分支),Mongoid(来自git)
>自定义Devise注册控制器,用于添加强参数的定义.
车型/ user.rb:
class User include Mongoid::Document devise :database_authenticatable,:registerable,:recoverable,:rememberable,:trackable,:validatable,:token_authenticatable,:confirmable,:lockable,:timeoutable field :email,type: String,default: '' ... has_one :profile accepts_nested_attributes_for :profile end
车型/ profile.rb:
class Profile include Mongoid::Document include Mongoid::Timestamps # Attributes # ---------- field :slug,default: '' # Acts as user-'friendlier' slug field :birthday,type: DateTime,default: DateTime.now field :first_name,default: '' field :occupation_title,default: '' belongs_to :user embeds_many :photos has_one :occupation_industry,:as => :industry end
控制器/用户/ registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController def resource_params params.require(:user).permit(:email,:password,:password_confirmation,:profile_attributes) end private :resource_params end
的routes.rb
devise_for :users,:path => '',:path_names => { :sign_in => 'login',:sign_out => 'logout',:sign_up => 'register' },:controllers => { :registrations => "users/registrations",:passwords => "users/passwords" }
我已经查看了这些相关帖子,他们似乎没有帮助:
> Rails 4 Nested Attributes Unpermitted Parameters
> https://gist.github.com/kazpsp/3350730
编辑:
看起来Devise确实支持其“rails4”分支中的强参数(它应该在几天内合并到master中.)查看代码,看起来你可以为设计控制器上的每个动作覆盖params函数.对于创建新用户,在我的示例中使用sign_up_params而不是resource_params.
尽管将此名称更改为正确的名称仍然无法正常工作…只使用此爆炸将所有参数列入白名单似乎有效:
def sign_up_params params.require(:user).permit! end
显然,这种方法违背了强参数的目的……所以现在的问题是如何允许我的嵌套属性profile_attributes(如我原来的问题所示)?
解决方法
我有完全相同的问题,并且压倒sign_up_params确实对我有用
def sign_up_params params.require(:user).permit(:email,:other,:etc) end
当然,不同之处在于我的只是标量值,而你正在尝试大量分配关系……我想这就是你应该寻找的地方.
顺便说一句,文档在这个主题中仍然不存在(太新),并且代码通知建议覆盖devise_parameter_sanitizer,这是不必要的.