【问题标题】:Rails build fields_for once inside fields_forRails 在 fields_for 中构建 fields_for 一次
【发布时间】:2013-03-08 00:12:17
【问题描述】:

在我的

<%= nested_form_for @object do |f| %>

我有一个类似的nested_form:

<%=f.fields_for :nested, :url => { :action => "new" } do |build| %>
   <%= render 'nested_fields', :f => build %>
<% end %>

在那个nested_field 里面,我还有另一个fields_for :nested2

我的问题是:我希望 nested2 在调用 nested 时出现 1 次。 我在嵌套控制器的新动作中尝试了

@nested = Nested.new
@nested.nested2.build

但这仅适用于“真正的”新动作。 这个问题有解决办法吗?

我正在使用“nested_form”gem。

【问题讨论】:

  • 我在理解您的问题时遇到了一些麻烦。您是否正在尝试为您的obkect(错字?)创建一个表单,然后其中有一个新的nested 对象,而该nested 对象也有一个用于新nested2 的嵌套表单?另外,您的fields_for 通话中的:url =&gt; { :action =&gt; "new" } 是什么意思?
  • 是的,你是对的 - 那只是一个错字。我现在更正了。该表单用于对象,并且它具有嵌套的内部。只要我点击链接,就可以经常添加这个嵌套。例如:我有一张发票,里面有我想要的任意多的文章。为了将它们结合起来,我使用了一个单独的表,其中包含 invoice_id 和 article_id 以及文章的数量。现在,当我想用​​新文章添加新发票时,我需要填写单独表格中的“计数”字段。希望现在更清楚我要做什么?

标签: ruby-on-rails nested-forms fields-for


【解决方案1】:

fields_for 允许您指定要为其呈现字段的特定对象,因此如果您希望您的 nested_fields 部分包含单个新构建的 nested2 模型的嵌套字段,您可以在 @987654324 中执行此操作@调用自己,像这样:

# '_nested_fields.html.erb'

...
<%= f.fields_for :nested2, f.object.build_nested2 do |build| %>
  <%= ... %>
<% end %>

这是假设Nestedhas_one :nested2,如果它是has_many 关联,fields_for 参数会略有不同:

<%= f.fields_for :nested2s, f.object.nested2s.build do |build| %>

f.object 允许您访问表单构建器的对象,然后您可以使用它的关联方法(基于关联类型)在该点构建新对象。

【讨论】:

  • 就我而言,这是一个 has_many 关联。在这个论点上我必须改变什么?
  • 我已经更新了我的答案以涵盖任何一种情况。不过,从你上面的描述来看,我不太明白你为什么需要一个 has_many 关联(尽管我认为我仍然错过了你想要实现的目标)。
  • 这几乎与我试图实现的上述情况完全相同。我有对象发票、文章和“invoice_articles”。最后一个具有“belongs_to”关联,前两个具有“has_many :through”关联。您更改的解决方案引发了以下异常:未定义的方法 `invoice_articles'
  • 所以Invoice has_many :articles, through: :invoice_articlesArticle has_many :invoices, through: :invoice_articles?他们都有has_many :invoice_articles吗?
  • 完全正确 - 这是我的实际关联模式。在发票和文章中,我还添加了“accepts_nested_attributes_for :invoice_articles”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多