开发者

How to use group_by with fields_for in rails?

I have a model with many children (selections). I need to display the children using fields for but I really want to group them based on an attribute on each selection using group_by.

Currently I am using

accepts_nested_attributes_for :selections, :allow_destroy => true

So my form looks a bit like this:

<% form_for @match do |form| %>
  <% form.fields_for :selections do |child_form| %>
    <%= child_form.object.first_name %>
    <%= child_form.check_box '_delete' %>
    <%= child_fo开发者_StackOverflow中文版rm.label '_delete', 'Remove' %>
  <% end %>
  <%= form.submit %>
<% end %>

Not quite sure how I could group the :selections using group_by. Any advice?


The question is a little vague. My interpretation is that you want to group similar selections by attribute as they appear in the form. Kind of like this:

  • form for Match
    • form for Selections
      • fields for Selection with attribute A
      • fields for Selection with attribute A
      • fields for Selection with attribute A
      • fields for Selection with attribute B
      • fields for Selection with attribute B
      • fields for Selection with attribute C
      • etc.

The group_by operator is not what you want. It will condense all selections that meet the criteria to a single entry.

The better option would be to use the order option when populating the list for the selection. Might even work out better for you to specify that order in the association. This will do what you want without changing your form.

 has_many :selections, :order => "attribute"

But this will cause all your selection queries from match to be ordered by attributes. If this is a problem, you could add a second has_many relationship for selections.

 has_many :selections
 has_many :grouped_selections, :class_name => "selection", :order => "attribute"

 accepts_nested_attributes_for :selections, :grouped_selections :allow_destroy => true

And all that needs to change in your form is <% form.fields_for :grouped_selections %>.


The only option I see is to group them through the association. In your model:

has_many :selections, :order => 'attribute DESC'

It's not the cleanest way to do it (that's how the selections will automatically be ordered throughout the rest of your application, too), but it'll work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜