对sets_by使用accepts_nested_attributes_for

时间:2013-01-27 20:14:23

标签: ruby-on-rails ruby rails-activerecord

我试图在我的模型中使用accepts_nested_attributes_for方法,但是我需要渲染按另一个关联分组的记录。我有这个工作,但我使用的方法似乎有点像黑客。

有没有更好的方法来构建它?

我的模特

  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

我的观点

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

1 个答案:

答案 0 :(得分:1)

你可以摆脱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 %>

quantities_for_size作为第二个参数传递给fields_for,应该使用它而不是与配方关联的整个quantitiesSee the docs on #fields_for了解更多信息。