Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I would like to be able to sort first by updated_at, then, if multiple items occur on the same day, sort by Price.

like image 890
NullVoxPopuli Avatar asked Aug 27 '10 20:08

NullVoxPopuli


People also ask

What is multicolumn sort?

Multicolumn sorting allows you to sort the fields one after the other. For example, if a user has three different fields rendered in the pivot grid, then it is possible to sort like: OrderBy(field1).

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…

How do you add multiple columns in rails?

command to create new model and table with columns : rails g model ModelName col_name1:string col_name2:integer col_name3:text ... command to add more columns under existing table: rails g migration AddColumnToModelName col_name4:string col_name5:integer ...


2 Answers

In Rails 4 you can do something similar to:

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

foo and bar are columns in the db.

like image 74
Christian Fazzini Avatar answered Sep 30 '22 01:09

Christian Fazzini


Assuming you're using MySQL,

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

Note the distinction from the other answers. The updated_at column will be a full timestamp, so if you want to sort based on the day it was updated, you need to use a function to get just the date part from the timestamp. In MySQL, that is DATE().

like image 45
Daniel Vandersluis Avatar answered Sep 30 '22 01:09

Daniel Vandersluis