在 select 子句中排序,以支持多列
我想根据以下条件从用户表中选择用户:
user.created
user.sales_count
因此,我想获取所有用户,有时按创建日期排序,有时根据 sales_count 排序。我希望能够在 ASC 或 DESC 顺序之间切换。
所有查询都需要有这个 WHERE 子句:
WHERE region = 123
How can I build my active record query to support those order by criteria?
I want to select users from the users table based on:
user.created
user.sales_count
So I want to fetch all users, sometimes ordered by created date, and sometimes based on sales_count. And I want to be able to switch between ASC or DESC order.
All queries need to have this WHERE clause:
WHERE region = 123
How can I build my active record query to support these order by conditions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
options[:order_col] ||=
实际上是在说:options[:order_col] = options[:order_col] || ""
的英文意思是将
options[:order_col]
设置为options[:order_col]
(如果已设置),否则""
。我们可以将 order_type 设置为""
因为 SQL 默认情况下会对结果进行 ASC 排序。例子:
options[:order_col] ||=
is really saying:options[:order_col] = options[:order_col] || ""
which in english is saying set
options[:order_col]
tooptions[:order_col]
if set, other wise""
. We can set the order_type to""
because SQL will by default order results ASC.Example: