gpt4 book ai didi

ruby-on-rails - Rails - 如何通过表单拆分嵌套属性?

转载 作者:行者123 更新时间:2023-12-02 09:20:55 25 4
gpt4 key购买 nike

我知道我们可以使用 fields_for 为嵌套属性创建字段的子部分。但是,我想通过表格将它们分开。我怎样才能做到这一点?

例如:

假设我有一个带有嵌套 bar 模型的模型 foo,如下所示:

    class Foo < ApplicationRecord
has_many :bars
accepts_nested_attributes_for :bars
end

一般观点是这样的:

    <%= form_for @foo do |f| %>
<!-- foo fields -->

<%= f.fields_for :bars do |f_bar| %>
<!-- bar fields -->
<% end %>

<%= f.submit "Submit" %>
<% end %>

但出于美观原因,我不希望所有聚集在一处。我想做这样的事情:

    <%= form_for @foo do |f| %>
<!-- foo fields -->

<%= f.fields_for :bars do |f_bar| %>
<!-- bar fields of one bar -->
<% end %>

<!-- other foo fields -->

<%= f.fields_for :bars do |f_bar| %>
<!-- bar fields of another bar -->
<% end %>

<!-- The previous repeats many more times in a non predictable way -->

<%= f.submit "Submit" %>
<% end %>

因此,如果我不必一次显示所有,这对我来说将是完美的。有人知道怎么做吗?

最佳答案

所以,我所需要的只是让 fields_for 每次只显示一个实例。

我发现 fields_for 允许您指定一个特定的对象来呈现字段。所以,我只是创建了一个计数器并每次添加一个 @foo.bars[counter] 并且它神奇地工作了,它是这样的:

    <% counter = 0 %>
<%= form_for @foo do |f| %>

<!-- foo fields -->

<%= f.fields_for :bars, @foo.bars[counter] do |f_bar| %>
<!-- bar fields of one bar -->
<% end %>
<% counter+=1 %>

<!-- other foo fields -->

<%= f.fields_for :bars, @foo.bars[counter] do |f_bar| %>
<!-- bar fields of another bar -->
<% end %>
<% counter+=1 %>

<!-- The previous repeats many more times in a non predictable way -->

<%= f.submit "Submit" %>
<% end %>

关于ruby-on-rails - Rails - 如何通过表单拆分嵌套属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42661126/

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