[英]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) 我想按两列排序,一列是DateTime( updated_at
),另一列是十进制(价格)
I would like to be able to sort first by updated_at, then, if multiple items occur on the same day, sort by Price. 我希望能够先使用updated_at进行排序,然后,如果同一天出现多个项目,则按价格排序。
In Rails 4 you can do something similar to: 在Rails 4中,你可以做类似的事情:
Model.order(foo: :asc, bar: :desc)
foo
and bar
are columns in the db. foo
和bar
是db中的列。
Assuming you're using MySQL, 假设您正在使用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. updated_at
列将是一个完整的时间戳,因此如果要根据更新的日期进行排序,则需要使用函数从时间戳中获取日期部分。 In MySQL, that is DATE()
. 在MySQL中,即DATE()
。
Active Record Query Interface lets you specify as many attributes as you want to order your query: Active Record Query Interface允许您指定要为查询订购的任意数量的属性:
models = Model.order(:date, :hour, price: :desc)
or if you want to get more specific (thanks @zw963 ): 或者如果你想更具体(感谢@ 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)
Actually there are many ways to do it using Active Record. 实际上有很多方法可以使用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: SQL仅在一步中生成:
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 您无需声明数据类型,ActiveRecord可以顺利地执行此操作,您的数据库引擎也是如此
Model.all(:order => 'updated_at, price')
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. 假设您在products表中有许多列,包括:special_price和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: 其次,在Product Controller中,添加执行搜索所需的位置:
@search = Product.sorted_by_special_price_asc_msrp_asc.search(search_params)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.