我使用Mongoid有点新,但对ActiveRecord有很多经验。我有以下型号
def Company
field :name
has_one :owner, autosave: true, class_name: 'User', inverse_of: :company
accepts_nested_attributes_for :owner
end
def User
belongs_to :company, inverse_of: :owner
has_one :profile
end
我的RegistrationController具有以下方法
def new
@company = Company.new
@company.build_owner
@company.owner.build_profile
respond_with @company
end
在我看来......
= simple_form_for @company, url: user_registration_path do |f|
= f.error_notification
.inputs
= f.simple_fields_for @company.owner do |o|
= o.input :email, required: true, autofocus: true
= o.simple_fields_for @company.owner.profile do |p|
= p.input :first_name, required: true
= p.input :last_name, required: true
= f.input :name, label: 'Company Name'
= f.input :subdomain
= o.input :password, required: true
= o.input :password_confirmation, required: true
.actions
= f.button :submit, "Sign up"
每当我提交此表格时,都会返回参数:
{"utf8"=>"✓",
"authenticity_token"=>"6z8+evYUwZwx3iADFewsMHiPl00vT7Eq6WaD8BOnQBc=",
"company"=>
{"user"=>
{"email"=>"testing@testing.com",
"profile"=>{"first_name"=>"testing", "last_name"=>"testing"},
"password"=>"testing",
"password_confirmation"=>"testing"},
"name"=>"testing",
"subdomain"=>"testing"},
"commit"=>"Sign up",
"action"=>"create",
"controller"=>"users/registrations"}
首先,我不明白为什么用户属性具有密钥:user,不应该是:user_attributes或:owner_attributes? mongoid网站上的例子似乎暗示了这一点。其次当我做公司= Company.new(params [:company])并在该对象上做company.owner时,我得到一个零对象。但是,做company.user会返回正确的用户对象。我已经发现,如果在params中密钥是:owner(而不是:user),则关联应该正常工作。但默认情况下不会发生这种情况。也许这与simpleform有关?非常感谢任何帮助!
答案 0 :(得分:0)
该字段应调用owner
,因为这是模型中字段的名称。
当你调用user
时会发生什么?mongoid会在模型中创建一个动态字段 - company[user]
。如果使用得当,这是正确的行为和非常强大的工具。
我不知道simple_form
但是在标准导轨中执行此操作的方法是调用f.fields_for :owner
,它应该为您提供所期望的功能。