Posts [ 7 ]

Topic: Passing additional variables from view to controller for layout.

In the view on for action index I have a table. The table can be sorted via the columns (ascending/descending). Say I have columns "date", "title", "age" that can be sorted. I was curious how I would pass variables like "column" ("date", "title", or "age") and "sort" ("asc" or "desc") to the controller to redisplay the same action and view but with the data reordered.Since I have to do this on the index action and no params[:id] variable is needed, I am just passing something like "title-asc" through to the controller from the view in the :id variable place ...

<%= link_to "Title Ascending", :id => "title-asc" %>

and then in the controller under the 'index' action I am splitting the variables ...

Re: Passing additional variables from view to controller for layout.

Re: Passing additional variables from view to controller for layout.

Pass through a parameter called 'order', which is set to the value of whatever you want to put into the :order option in the find call, which in turn is whatever would follow 'order by' in an sql query.

As ever in this sort of situation, start with the controller and then tailor the view to the controller. I'm using the example model name of cars since i don't know what your model is called.

Now you just need to make sure the view sends through a value for params[:order]. There's a lot of different ways of doing this. A simple way is to make your 're-order' links to all just be links to the cars index page, and set the order parameter differently in each. In this example i also assume you have a little up and down arrow graphic in images called 'up.png' and 'down.png'. This is what the user will actually click on.

For the desc links, you usually want to show the asc (default) version in every situation except where params[:order] is currently equal to that field. ie, when you sorted by that field last time. eg