2017-03-08 63 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'的數量在每種情況下都不相同。對於混淆的解釋:/ –