blu
blu

Reputation: 13185

How can I sort the children of option_groups_from_collection_for_select in Rails

I have a select list with optgroups and child options rendered from option_groups_from_collection_for_select

This works fine but I don't see any way to specify the sort order of each child section in any documentation. I'd prefer not to have to resort to mapping and sorting myself; I would think this would be a common enough need to be part of the helper.

How can I sort the children in each grouping?

Upvotes: 3

Views: 219

Answers (1)

Michael Chaney
Michael Chaney

Reputation: 3041

Declare an order in your has_many. Taking the example in the api doc http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-option_groups_from_collection_for_select you could do this:

class Continent < ActiveRecord::Base
  has_many :countries, -> { order("countries.name") }
end

class Country < ActiveRecord::Base
  belongs_to :continent
end

If you want specialized data in a collection_select it's usually easiest to handle it in the model.

Upvotes: 4

Related Questions