Forum: Ruby on Rails Sort or Order a <Select> box.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Andy P. (Guest)
on 2005-12-31 23:00
Evening folks,

I'm new to RoR, and have found some very useful info on this site,
thanks.

I have a select box that I need to sort.

<select name="people[peoplekind_id]">
<% @peoplekinds.each do |peoplekind| %>
<option value="<%= peoplekind.id %>"
<%= ' selected' if peoplekind.id == @people.peoplekind_id %>>
<%= peoplekind.name %>
</option>
<% end %>
</select></p>
<input type="submit" value="Update" />

In the controller for the List page I am able to use,  :order_by =>
'name' , under the Def List.

 I have tried this in <% @peoplekinds.each do |peoplekind| %> above,
but this does not work. How far off track am I?

Kindest regards.
Benjamin S. (Guest)
on 2005-12-31 23:51
(Received via mailing list)
> In the controller for the List page I am able to use,  :order_by =>
> 'name' , under the Def List.

When you retrieve @peoplekinds, either use sort_by or pass the :order
=> 'name' parameter when you call your model's find method.

You can also use options_from_collection_for_select(@peoplekinds,
"id", "name", @people.peoplekind_id) to generate all the <option>
tags for you; see http://api.rubyonrails.com/classes/ActionView/
Helpers/FormOptionsHelper.html#M000356.

-Ben
Steve R. (Guest)
on 2006-01-01 02:54
(Received via mailing list)
I've found this kind of construct works (where arg might be your AR).

options_for_select(arg.sort{|k,v| k[1] <=> v[1]}, selected)

So, perhaps you'd be using:

options_for_select(people.sort{|k,v| k[1] <=> v[1]},
@people.peoplekind_id)

Hope this helps...
Andy P. (Guest)
on 2006-01-02 07:47
Thanks for the info, and thanks to those that emailed me with help.

The above two examples seem to be beyond me, but made for interesting
reading, I have homework to do.

The soloution I came up with was to include the following under the
controller for the page in question,

@peoplekind_pages, @peoplekinds = paginate(:peoplekinds, :order_by =>
'name', :per_page => 30)

This seems to work but I'm gussing it is not a very ellegant approach,
as I will have to repeat this under all the

def's ....

end

that it needs to appear in.

Thanks again.
This topic is locked and can not be replied to.