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

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

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

    lets say you have many columns in the products table including: special_price and msrp. These are the two columns we are trying to sort with.

    Okay, First in your Model add this line:

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

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

    @search = Product.sorted_by_special_price_asc_msrp_asc.search(search_params)
    

提交回复
热议问题