[英]“Unpermitted Parameters” using nested attributes and a has_one :through relationship
[英]Accepts Nested attributes using mongoid for has_one relationship
我對使用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有關? 任何幫助深表感謝!
該字段應稱為owner
因為它是模型中字段的名稱。
當你稱之為user
時會發生什么,mongoid會在模型中創建一個動態字段 - company[user]
。 正確使用時,這是正確的行為和非常強大的工具。
我不知道simple_form
但在標准rails中執行此操作的方法是調用f.fields_for :owner
,它應該為您提供所期望的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.