正确实例化嵌套 fields_for 而不显示较旧的保存对象?

发布于 2024-09-29 00:29:54 字数 685 浏览 0 评论 0原文

我有一个嵌套表单,实例化如下:

- 2.times { @organization.referrals.build }
- form_for @organization do |f|
  = f.error_messages
  - f.fields_for :referrals do |f|

除了,嵌套表单应该始终是新的和唯一的。这种形式也显示了以前创建的对象。

所以我尝试这样写..

- 2.times { @organization.referrals.build }
- form_for @organization do |f|
  = f.error_messages
  - f.fields_for @organization.referrals.select{|r| r.new_record? } do |f|

但现在我没有看到 2 个空白表单,并且我无法保存我的对象,因为它尝试传递 Organization.referral (这不是一种方法)而不是Organization.referrals

问题 1

如何创建 2 个空白表单?

问题 2

我如何才能正确通过(如第一个示例中所示)?

I have a nested form that instantiates as this :

- 2.times { @organization.referrals.build }
- form_for @organization do |f|
  = f.error_messages
  - f.fields_for :referrals do |f|

Except, the nested forms are supposed to be always new and unique. Where as this form shows previously created objects as well.

So I tried to write as so..

- 2.times { @organization.referrals.build }
- form_for @organization do |f|
  = f.error_messages
  - f.fields_for @organization.referrals.select{|r| r.new_record? } do |f|

But now I do not see 2 blank forms, and I can not save my object because it tries to pass Organization.referral (which is not a method) instead of Organization.referrals .

Question 1

How do I create 2 blank forms?

Question 2

How do I get this to pass correctly ( as it does in the first example ) ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡笑忘祈一世凡恋 2024-10-06 00:29:54

试试这个:

模型

class Organization < ActiveRecord::Base
  has_many :referrals
  accepts_nested_attributes_for :referrals
end

视图

<%= form_for @organization do |f| %>
  <% 2.times do |i| %>
    <%= f.fields_for :referrals, @organization.referrals.build, :index => i do |rf| %>
       <%= rf.text_field :some_referral_attribute %>
    <% end %>
  <% end %>
<% end %>

Try this:

model

class Organization < ActiveRecord::Base
  has_many :referrals
  accepts_nested_attributes_for :referrals
end

view

<%= form_for @organization do |f| %>
  <% 2.times do |i| %>
    <%= f.fields_for :referrals, @organization.referrals.build, :index => i do |rf| %>
       <%= rf.text_field :some_referral_attribute %>
    <% end %>
  <% end %>
<% end %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文