我对使用 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 = Company.new(params[:company]) 并执行 company.owner 时,我得到一个 nil 对象。但是,执行 company.user 会返回正确的用户对象。我发现如果参数中的键是:owner(而不是:user),则关联应该可以正常工作。但默认情况下不会发生这种情况。也许这与简单形式有关?任何帮助深表感谢!