1

This should be an easy lookup, but I can't seem to find it anywhere in the documentation.

As of right now, everything rendered in the select is ordered by id, but I'd like it to render an alphabetical list instead (to make it more human-scannable).

The code I'm currently using to generate the select:

<%= f.collection_select :item_id, Item.all, :id, :name %>

Karma points for a generalized answer that can apply to any attribute of Item (not just alphabetically by :name).

Currently using Rails v 3.0.5

jasonmklug
  • 1,584
  • 2
  • 15
  • 28

2 Answers2

0

There is another question here that might be able to help, although I have yet to try it. If you try based on this example (from the previous site), hopefully sorting in the form will work for you:

class Log < ActiveRecord::Base
  has_many :items, :order => "some_col DESC"
end
Community
  • 1
  • 1
TheDude
  • 3,796
  • 2
  • 28
  • 51
0

You can do this in the model like the other answer to set the default ordering:

has_many :items, :order => "some_col DESC"

Or if you need to deviate from the default order, you can also set it in the controller and access in the view:

controller.rb

def index
  @items = Item.all(:order => 'some_col DESC')
end

index.erb

<%= f.collection_select :item_id, @items, :id, :name %>


Another option is you can do a named scope inside your model for ordering:

item.rb

named_scope :alphabetically, :order => "some_col DESC"

index.erb

<%= f.collection_select :item_id, Item.alphabetically, :id, :name %>
Chris Barretto
  • 9,379
  • 3
  • 42
  • 45