我有一个business
模型,其中has_one address
我正在尝试构建一个在创建业务时接受地址属性的表单。我收到错误
无法批量分配受保护的属性:地址
以下是我的模特
商家
class Business<ActiveRecord::Base
has_one :address, :as => :addressable
attr_accessible :name, :email, :address_attributes, :password, :password_confirmation
validates_presence_of :address
validates_associated :address
accepts_nested_attributes_for :address
end
地址
class Address<ActiveRecord::Base
attr_accessible :line1, :city, :zip
validates_presence_of :line1, :city, :zip
belongs_to :addressable, polymorphic: true
end
查看
%h2 Sign up
= form_for(:business, :url => business_registration_path) do |f|
= devise_error_messages!
%div
= f.label :name
%br/
= f.text_field :name
%div
= f.label :email
%br/
= f.email_field :email
%div
= f.label :password
%br/
= f.password_field :password
%div
= f.label :password_confirmation
%br/
= f.password_field :password_confirmation
%div
=f.fields_for :address do |address|
=render :partial => 'businesses/shared/address', :locals => {:f => address}
%div= f.submit "Sign up"
= render :partial => "devise/shared/links"
部分视图
%div
= f.label :line1, 'Address 1'
%br/
=f.text_field :line1
%div
= f.label :city
%br/
= f.text_field :city
%div
= f.label :zip, 'Postal Code'
%br/
= f.text_field :zip
原始POST数据这就是我在想的问题
Parameters: {"utf8"=>"✓", "authenticity_token"=>"/h17NgMDr4VCTDd+FxGlAI4RWmfAat9guU9q00hYIA4=", "business"=>{"name"=>"hello", "email"=>"hello@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "address"=>{"line1"=>"this is line1", "city"=>"Andra", "country"=>"Jama", "zip"=>"123123"}}, "commit"=>"Sign up"}
地址字段不应该像这样
"address_attributes"=>{"line1"=>"this is line1", "city"=>"Andra", "country"=>"Jama", "zip"=>"123123"}
为什么生成地址而不是address_attributes?这可能会导致问题。有任何想法吗?我一直在努力奋斗大约2个小时。赞赏任何建议或解决方案。
Upadte1:
如果我在视图中进行了更改并使用
=f.fields_for :address_attributes do |address|
而不是
=f.fields_for :address do |address|
Everythings开始工作,但这并不是所有教程和文档都在讨论的内容?
答案 0 :(得分:3)
您应该将对象(Business
类的实例)传递给form_for
而不是符号:
= form_for(@business, :url => business_registration_path) do |f|
据推测,您将在控制器操作中拥有@business = Business.new
。
Business
类包含所有验证和关联逻辑。当您需要无模式表单时使用符号(Rails不会推断:business
引用Business
类,即使它们共享相同的名称。)