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

前端 未结 7 1108
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 23:39

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, t

7条回答
  •  孤城傲影
    2020-12-01 00:12

    Actually there are many ways to do it using Active Record. One that has not been mentioned above would be (in various formats, all valid):

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

    Maybe it's more verbose, but personally I find it easier to manage. SQL gets produced in one step only:

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

    Thusly, for the original question:

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

    You need not declare data type, ActiveRecord does this smoothly, and so does your DB Engine

提交回复
热议问题