Is there an elegant way to implement a sort asc and desc actions in the views/controller in rails?
What I have is the common index.html.erb view that lists all of my data of certain model and I want to add some small buttons (or make the title clickable) to sort the list ascending or descending of that column. I am wondering if there is an elegant and efficient way to do it or should I just add a new controller for every column (or button) I want this action to happen.
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.
To sort a result set in ascending order, you use ASC keyword, and in descending order, you use the DESC keyword. If you don't specify any keyword explicitly, the ORDER BY clause sorts the result set in ascending order by default.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Here are two examples that I'm using. The first one with @plans
is where I just want to order a decimal from lowest to highest. The other example is a bit more complicated where I want to order user files from newest to oldest. I then used a second variable to group the files by the date created. Both examples where performed in the controllers.
@plans = Plan.order("price") @files= @user.files.order("id DESC").all @dates = @files.group_by { |t| t.created_at }
For clickable buttons in your view, check out Ryan Bates's Railscast episode covering this information.
http://railscasts.com/episodes/228-sortable-table-columns
I recently used a gem called sorted
with good results in case you want to use a pre-packaged solution for this instead of rolling out your own.
https://github.com/mynameisrufus/sorted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With