在我的应用中,用户有一个位置,位置属于用户。
用户.rb
has_one :location
accepts_nested_attributes_for :location
attr_accessible ... :location_attributes
位置.rb
belongs_to :user
attr_accessible :country, :state, :city, :address, :zipcode, :user_id
users_controller(用户是自动创建的,所以没有“新”视图)
def edit
@user = current_user
@user.build_location
end
用户/edit.html.haml
= form_for @user do |f|
...
= f.fields_for :location do |location|
%p
= location.label :country
= location.text_field :country
%p
= location.label :state
= location.text_field :state
%p
= location.label :city
= location.text_field :city
%p
= location.label :address
= location.text_field :address
%p
= location.label :zipcode
= location.text_field :zipcode
= f.submit
我得到的错误是“无法批量分配受保护的属性:国家、州、城市、地址、邮政编码。”
我之前遇到过“无法批量分配受保护的属性:location_attribute”类型的错误,但这不是问题所在。
这是我的(删节)参数:
{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"RTpnMsKuByhnGgs9xrX3d0nzKzcaqIcpS75tsujPX2s=", "user"=>{"name"=>"myname", ... "location_attributes"=>{"country"=>"USA", "state"=>"whatever", "city"=>"", "address"=>"", "zipcode"=>""}}, "commit"=>"Update account", "action"=>"update", "controller"=>"users", "id"=>"219"}