Karl Entwistle
Karl Entwistle

Reputation: 941

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. I have got this to work but the method I have used seems like a bit of a 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 %>

Upvotes: 1

Views: 96

Answers (1)

m_x
m_x

Reputation: 12564

You can get rid of the if builder.object.size == size part with this :

<% @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. See the docs on #fields_for for more information.

Upvotes: 1

Related Questions