Rails-如何通过表单拆分嵌套属性



我知道我们可以使用fields_for来创建嵌套属性的字段小节。但是,我想通过表格分开它们。我该怎么做?

例如:

假设我有一个带有嵌套条模型的模型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 %>

但是出于美学原因,我不希望所有bars在一个地方进行结合。我想做类似的事情:

    <%= 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 %>

,如果我不必一次显示所有bars,这对我来说是完美的。有人知道如何?

所以,我所需要的只是使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 %>

您可以使用fields_for的第二个参数并传递范围:

class Bar < ApplicationRecord
  belongs_to :foo
  scope :some_a,->{where(conditions)}
  scope :some_b,->{where(conditions)}
end

在您的表格中

<%= form_for @foo do |f| %>
    <%= f.text_field :foo_attr %>
    <%= f.fields_for :bars, @foo.bars.some_a do |b| %>
        <%= b.hidden_field :other_bar_attr %>
        <%= b.text_field :bar_attr %>
        ...
    <% end %>
    <%= f.fields_for :bars, @foo.bars.some_b do |b| %>
        <%= b.hidden_field :other_bar_attr %>
        <%= b.text_field :bar_attr %>
        ...
    <% end %>
    <%= f.submit %>
<% end %>

您可以使用隐藏的输入来设置示波器中使用的默认值。

update

如果您需要在表格中使用多个fields_for实例,则可以执行此类操作

在控制器中设置了示波器对象的数组,一个示例可能是:

class SomeController < AP
  def some_action
    @var_to_the_form = []
    (1..well_know_quantity).each do |value|
      @var_to_the_form << Model.where(conditions)
    end
  end
end

,您的表格必须如下

<% @var_to_the_form.each do |records| %>
  <%= f.fields_for :bars, records do |b| %>
    <%= b.hidden_field :other_bar_attr %>
    <%= b.text_field :bar_attr %>
        ...
  <% end %>
<% end %>

重要的部分是知道如何将您传递给视图的记录设置。

最新更新