2

我有一个businesshas_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个小时。感谢任何建议或解决方案。

更新1:

如果我在视图中进行更改并使用

 =f.fields_for :address_attributes do |address|

代替

 =f.fields_for :address do |address|

Everythings 开始工作,但这不是所有教程和文档都在谈论的内容?

4

1 回答 1

3

您应该将对象(Business类的实例)传递给form_for而不是符号:

= form_for(@business, :url => business_registration_path) do |f|

想必,你@business = Business.new在控制器中会有动作。

该类Business包含所有验证和关联逻辑。当你想要一个无模式的表单时使用一个符号(Rails 不会推断它:business引用Business类,即使它们共享相同的名称)。

于 2012-05-22T12:21:15.137 回答