[英]Using accepts_nested_attributes_for with group_by
I am trying to use the accepts_nested_attributes_for method within my model, however I need to render the records grouped by another association. 我正在尝试在模型中使用accepts_nested_attributes_for方法,但是我需要呈现按另一个关联分组的记录。 I have got this to work but the method I have used seems like a bit of a hack.
我有这个工作,但我使用的方法似乎有点hack。
Is there a better way to structure this? 有没有更好的方法来构造它?
My Model 我的模特
has_many :quantities
has_many :ingredients, :through => :quantities, :uniq => true
has_many :sizes, :through => :quantities, :uniq => true
has_many :photos, :as => :imageable
accepts_nested_attributes_for :quantities
My View 我的观点
<%= form_for [:admin, @recipe] do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% @recipe.quantities.group_by(&:size).each do |size, quantities| %>
<h3><%= size.name %></h3>
<%= f.fields_for :quantities do |builder| %>
<% if builder.object.size == size %>
<p>
<%= builder.text_area :value, :rows => 1 %>
</p>
<% end %>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
You can get rid of the if builder.object.size == size
part with this : 您可以使用以下方法摆脱
if builder.object.size == size
部分:
<% @recipe.quantities.group_by(&:size).each do |size, quantities_for_size| %>
<h3><%= size.name %></h3>
<%= f.fields_for :quantities, quantities_for_size do |builder| %>
<p><%= builder.text_area :value, :rows => 1 %></p>
<% end %>
<% end %>
passing the quantities_for_size
as a second argument to fields_for
should make it use it instead of the whole quantities
associated to the recipe. 经过
quantities_for_size
作为第二个参数fields_for
应该让使用它,而不是整个的quantities
相关联的配方。 See the docs on #fields_for for more information. 有关更多信息, 请参见#fields_上的文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.