尝试将嵌套的自定义属性Profile(Mongoid 文档)添加到我的设计User类。当提交设计注册表单时,它应该同时创建一个用户和一个相应的配置文件对象。
我希望最终结果在我的 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
- 设计('rails4' 分支),Mongoid(来自 git)
- 自定义设计注册控制器,用于添加强参数的定义。
模型/用户.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, type: String, default: '' # Acts as user-'friendlier' slug
field :birthday, type: DateTime, default: DateTime.now
field :first_name, type: String, default: ''
field :occupation_title, type: String, 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
路线.rb
devise_for :users,
:path => '',
:path_names => {
:sign_in => 'login',
:sign_out => 'logout',
:sign_up => 'register'
},
:controllers => {
:registrations => "users/registrations",
:passwords => "users/passwords"
}
我已经看过这些相关的帖子,它们似乎没有帮助:
编辑:
看起来 Devise 确实在其“rails4”分支中支持强参数(应该在几天内合并到 master 中。)查看代码,您似乎可以为设计控制器上的每个操作覆盖 params 函数。对于创建新用户,它sign_up_params
而不是resource_params
在我的示例中。
尽管将此名称更改为正确的名称,但它仍然不起作用......仅使用此 bang 将所有参数列入白名单似乎有效:
def sign_up_params
params.require(:user).permit!
end
显然,这种破坏了强参数的目的......所以现在的问题是我如何允许我的嵌套属性profile_attributes
(如我原来的问题所示)?