Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using group_by with fields_for and accepts_nested_attributes_for

I have a the following rails models:

class Release < ActiveRecord::Base
    has_many :release_questionnaires, :dependent => :destroy
    accepts_nested_attributes_for :release_questionnaires
    ...
end class

class ReleaseQuestionnaire < ActiveRecord::Base
    belongs_to :release
    belongs_to :milestone
    ...
end class

In my view code, I have the following form.

<% form_for @release, ... do |f| %>
  ...
  <table class="questionnaires">
    <% f.fields_for :release_questionnaires, @release.release_questionnaires.sort_by{|ra| ra.questionnaire.name} do |builder| %>
      ...
    <% end %>
  </table>
<% end %>

This works and allows me to view and edit the questionnaires as desired. However, I have an additional requirement to break the questionnaires out into their own tables grouped by the milestone they are associated to, rather than in a single table. It appears as though the group_by method is design to accomplish this, but I cannot get it to work as desired inside the tag.

It may be that I'm missing something obvious, as I am a beginner... Any help is appreciated.

like image 596
Derek Prior Avatar asked Apr 12 '10 22:04

Derek Prior


1 Answers

Is this what you're looking for?

<% form_for @release, ... do |f| %>
  ...
  <% @release.release_questionnaires.group_by {|rq| rq.milestone }.each do |milestone, questionnaires_group| %>
    <table class="questionnaires">
      <% f.fields_for :release_questionnaires, questionnaires_group.sort_by{|rq| rq.name} do |builder| %>
        ...
      <% end %>
    </table>
  <% end %>
<% end %>
like image 99
mckeed Avatar answered Nov 01 '22 02:11

mckeed