Rails中的三个模型嵌套属性

时间:2016-03-02 09:34:20

标签: ruby-on-rails ruby ruby-on-rails-3.2

我有3个模型,我将其命名为Country, Province, MunicipalityCountry位于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]。我的错误是什么?

谢谢!

1 个答案:

答案 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 不同。