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 %>
&开发者_Python百科lt;/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.
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 %>
精彩评论