我知道我們可以使用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
一次。有人知道如何做到這一點?
你試過了嗎? –
您可以嘗試像使用'@ foo'完成的那樣傳遞實例變量。將單條濾除爲一個實例變量,並放在控制器中的另一個變量中,您可以在視圖中使用該變量。 – vee
單個變量的數量未確定。這只是一個例子.. –