Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to implement sort asc or desc in rails

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.

like image 999
marimaf Avatar asked Mar 25 '12 04:03

marimaf


People also ask

Can we use ASC and DESC together in SQL?

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.

Which combination is used to sort result in descending 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.

Which of the following is the default sorting order in MySQL?

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


2 Answers

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

like image 84
kobaltz Avatar answered Sep 21 '22 10:09

kobaltz


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

like image 33
Carlos Ramirez III Avatar answered Sep 20 '22 10:09

Carlos Ramirez III