views:

53

answers:

1

I'm a newcomer to Rails. I want to build a simple form that determines the sort order of a list. I've implemented a form in the likes of -

<%= radio_button_tag :sort, "rating" %>
  <%= label_tag :sort_rating, "order by rating" %>
<%= radio_button_tag :sort, "name" %>
  <%= label_tag :sort_name, "order by name" %>

And now I am unsure how to implement the sort at the controller/model level. The aspects I am puzzled about are:

  • Where should the sort be performed
  • How could the sort parameter be persisted
  • How could the code be reused

Right now, I can't even get the selected sort method to remain selected after a submit.

I would most appreciate any guidance or reference to an example.

+1  A: 

Where should the sort be performed

In controller:

order_by = "rating ASC" if params[:sort] == 'rating'
...
@people = Person.all(:order => order_by)

Or something like this. I'm not sure how are forms with radio buttons passed.

How could the sort parameter be persisted

In views:

<%= radio_button_tag :sort, "rating", params[:sort] == 'rating' ? true : false %>
...
klew
Do I have to write a bunch of order_by = ... if ... for every possible value? Can't I have the radio buttons somehow map to every value I want to sort by?
shmichael
I think that if you would set value of radio button exactly as a name of a column, then you can: `order_by = ["? ASC", param[:sort]]` in controller instead of many `if`s. I used an array, because then `param[:sort]` is sanitized.
klew