gpt4 book ai didi

ruby-on-rails-3 - 使用 accepts_nested_attributes_for 时,Rails 无法批量分配 protected 属性错误

转载 作者:行者123 更新时间:2023-12-04 05:45:50 25 4
gpt4 key购买 nike

我有一个 business有_one的模型address我正在尝试构建一个在创建业务时接受地址属性的表单。我收到错误

无法批量分配 protected 属性:地址

这是我的模型

业务

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"

局部 View
%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 而不是 address_attributes ?这可能是导致问题的原因。有什么想法吗?我已经为此苦苦挣扎了大约 2 个小时。感谢任何建议或解决方案。

更新:

如果我在 View 中进行更改并使用
 =f.fields_for :address_attributes do |address|

代替
 =f.fields_for :address do |address|

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

最佳答案

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

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

想必,你会有 @business = Business.new在 Controller Action 中。
Business类包含所有验证和关联逻辑。当你想要一个无模式形式时使用符号(Rails 不会推断 :business 指的是 Business 类,即使它们共享相同的名称)。

关于ruby-on-rails-3 - 使用 accepts_nested_attributes_for 时,Rails 无法批量分配 protected 属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10701662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com