2017-03-08 64 views
1

我知道我们可以使用fields_for为嵌套属性创建一个字段的子部分。不过,我想通过表格将它们分开。我怎样才能做到这一点?Rails - 如何通过窗体拆分嵌套属性?

例如:

假设我有一个模型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一次。有人知道如何做到这一点?

+1

你试过了吗? –

+0

您可以尝试像使用'@ foo'完成的那样传递实例变量。将单条滤除为一个实例变量,并放在控制器中的另一个变量中,您可以在视图中使用该变量。 – vee

+0

单个变量的数量未确定。这只是一个例子.. –

回答

0

所以,碰巧我所需要的只是让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 %> 
1

您可以使用fields_for第二PARAM和传递范围:

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

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

+0

我喜欢你的解决方案,但它并不真正适合我的问题,因为范围很多,并且不可预测。 –

+0

是说范围不可预测?或者你是否想说在你的视图中'fields_for'的数量在每种情况下都不一样? – rogelio

+0

'fields_for'的数量在每种情况下都不相同。对于混淆的解释:/ –