how to sort a collection with simple form

collections, ruby-on-rails-3, simple-form

Solution

Here is how you should update your code:

<%= f.association :category, collection: Category.order('name ASC') %>

This assumes you want to sort by the category name, in ascending order.

Problem

I'm pulling a list of categories from a model. In the admin section I want to use it to assign categories to products. It's working fine but the list shows in the order the categories have been added. I'd like to sort them alphabetically but I can't suss it out. I'm sure it's pretty simple (hopefully) here's my code: ``` <%= simple_form_for(@game) do |f| %> <%= f.input :name %> <%= f.input :description %> <%= f.input :copy %> <%= f.input :image %> <%= f.input :thumbnail %> <%= f.input :heroimage %> <%= f.association :category, collection: @categories %> <%= f.button :submit %> <% end %> ``` I tried to add a `.sort_by(desc)` or just `.sort` on the collection method but it doesn't change the list. Cheers

Original source

Related problems