我有3个模型,我将其命名为Country, Province, Municipality
,Country
位于Province
下,Municipality
位于Province
下。所以我做了这样的嵌套表格:
我的模特:
国家
has_one :province, dependent: :destroy
accepts_nested_attributes_for :province
省
belongs_to :country
has_many :municipalities, dependent: :destroy
accepts_nested_attributes_for :municipalities
市
belongs_to :province
我的计划应该是@country.province.municipalities.build
。但是当我这样做时:
@country = Country.new
@country.province.build
我已经NoMethodError: undefined method ``build' for nil:NilClass
。
更新:
我使用以下内容更改了Country
模型
has_many :provice, dependent: :destroy
accepts_nested_attributes_for :provinces
然后,我得到了我想要的东西:
@province = @country.provinces.build
@province.municipalities.build
现在正在运作。但问题是当我看到我的观点时,看起来像是:
country[provinces_attributes][municipalities_attributes][name]
必须是:
country[provinces_attributes][municipalities_attributes][0][name]
我在这里错过了什么,失去了[0]
?
更新2
在我看来:
<%= form_for @country, :html => {:multipart => true} do |f| %>
<%= f.fields_for :province_attributes do |p| %>
<%= f.fields_for :municipalities_attributes do |m| %>
<%= m.text_field :name %>
<% end %>
<% end %>
<% end %>
我希望text_field名称应该为country[province][municipalities][0][name]
,但不会输出[0]
,country[province][municipalities][name]
。我的错误是什么?
谢谢!
答案 0 :(得分:0)
我的计划应该是@ country.province.municipalities.build。但是当我 做:
@country = Country.new @ country.province.build我有NoMethodError: 未定义的方法``build'为nil:NilClass
当你有:
has_one :province, dependent: :destroy
如果没有记录,ActiveRecord将返回 nil 。当你尝试:
@province = @country.province.build
在 @country 上调用省后,你得到nil,因此 NoMethodError:未定义的方法``build'为nil:NilClass
而只是使用:
@province = @country.build_province
此方法仅对 has_one 关联
有效在 has_many 关联的情况下,您不需要执行此操作,因为当您想要构建has_many的新实例时(就像您在此处所做的那样):
@country.provinces.build
ActiveRecord将返回一个ActiveRecord :: Associations :: CollectionProxy的空实例(实际上是[]的一个轨道增强版本 - 一个空数组)。 CollectionProxy实现了构建方法,与has_one关联时的 nil 不同。