3

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

Yannick Schall
  • 32,601
  • 6
  • 29
  • 42
  • I have the same issue. Explicitly sorted collection but renders it in a random fashion. Actually, it sorts by `value_method`. In my case it's the `id` column. – Amit Patel Oct 04 '21 at 13:08

2 Answers2

8

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.

user2397178
  • 441
  • 5
  • 4
4

I imagine @categories is assigned as an arel in your controller, can you add an .order("description") to that; e.g.

@categories = Category.order('description')
Mark Nadig
  • 4,901
  • 4
  • 37
  • 46
  • As it's an association, can I have the collection sorting in the Category controller,or does it need to live in the Game controller. Where i have put it for now? – Yannick Schall Apr 27 '12 at 16:37
  • 1
    It would need to live in the controller that is rendering. but, sounds like perhaps you want this association ordered always? Does this help: http://stackoverflow.com/questions/1127192/rails-order-by-in-associated-model – Mark Nadig Apr 27 '12 at 17:23
  • @categories = Category.order('description') works fine. I've implemeted active admin and now it's stopped working. Is it due to the admin namespace? – Yannick Schall Apr 30 '12 at 09:59
  • No idea... what does "it's stopped working" mean - just the order is off, or there's an error ? – Mark Nadig Apr 30 '12 at 16:02
  • hehehe sorry, it means it is not sorted anymore. but just when i'm in the active admin namespace. – Yannick Schall Apr 30 '12 at 16:17