Ruby on Rails: how do I sort two columns using ActiveRecord?

I want to sort by two columns, one is DateTime ( updated_at ) and the other is Decimal (Price)

I would like to be able to sort first by update_at, then if several items happen on the same day, sort by price.

+59
ruby-on-rails
Aug 27 '10 at 20:09
source share
7 answers

Assuming you are using MySQL,

 Model.all(:order => 'DATE(updated_at), price') 

Note the difference from the other answers. The updated_at column will be a complete timestamp, so if you want to sort based on the day it was updated, you need to use the function to get only a portion of the date from the timestamp. In MySQL, this is DATE() .

+57
Aug 27 '10 at 20:22
source share

In Rails 4, you can do something similar to:

 Model.order(foo: :asc, bar: :desc) 

foo and bar are columns in db.

+92
Oct 18 '13 at 8:45
source share
 Thing.find(:all, :order => "updated_at desc, price asc") 

will do the trick.

Update:

 Thing.all.order("updated_at DESC, price ASC") 

- current path. (Thanks @cpursley )

+40
Aug 27 '10 at 20:17
source share

Active Record Query Interface allows you to specify as many attributes as you want to order your query:

 models = Model.order(:date, :hour, price: :desc) 

or if you want more specific information (thanks @ zw963 ):

 models = Model.order({price: :desc}, {date: :desc}, {price: asc}) 

Bonus: after the first request, you can link other requests:

 models = models.where("date >= ?", Time.current.to_date) 
+18
Jul 12 '13 at 2:36 on
source share

There are actually many ways to do this using Active Record. The one that was not mentioned above will be (in different formats, all valid):

 Model.order(foo: :asc).order(:bar => :desc).order(:etc) 

This may be more verbose, but it’s easier for me personally to manage. SQL is created in just one step:

 SELECT "models".* FROM "models" ORDER BY "models"."etc" ASC, "models"."bar" DESC, "models"."foo" ASC 

So for the original question:

 Model.order(:updated_at).order(:price) 

You do not need to declare a data type, ActiveRecord does it smoothly, and your DB Engine

+13
Jan 11 '14 at
source share
 Model.all(:order => 'updated_at, price') 
+2
Aug 27 '10 at 20:16
source share

None of them worked for me! After exactly 2 days of looking at the top and bottom over the Internet, I found a solution!

lets say that there are many columns in the product table, including: special_price and msrp. These are the two columns that we are trying to sort.

Ok, first in your model add this line:

 named_scope :sorted_by_special_price_asc_msrp_asc, { :order => 'special_price asc,msrp asc' } 

Secondly, in the Product Controller add where you need to search:

 @search = Product.sorted_by_special_price_asc_msrp_asc.search(search_params) 
0
Aug 11 '16 at 18:54
source share



All Articles