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

前端 未结 7 1082
爱一瞬间的悲伤
爱一瞬间的悲伤 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:19

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

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

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

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

    Bonus: After the first query, you can chain other queries:

    models = models.where('date >= :date', date: Time.current.to_date)
    

提交回复
热议问题