在我的Code模型中,我编写了如下的作用域:
scope :recent, lambda { |n = 10| includes(:user).where('users.deleted_at' => nil).order("users.last_active_at DESC").limit(n) }
它基本上按code.users排序。Last_active_at at desc顺序。
工作得很好。现在,我想添加额外的条件。
如果用户。id=10000,我想用代码。Created_at代替code.user.last_active_at。那么排序条件就是
的组合 code.created_at
和
code.users.last_active_at
有可能吗?如果是这样,我如何更改我的代码?
在Mysql中,你可以使用CASE
语句,但不知道ruby,但你可以在纯查询中使用这种方式
ORDER BY CASE WHEN user.id=10000
THEN code.created_at
ELSE code.users.last_active_at
END
DESC