我有一个包含一组复杂范围的现有模型:
scope :test1 , where(gift: true)
scope :test2 , lambda {|time| where("last_created_at > ?", time)}
scope :test3 , where(approved: true)
我可以做一些像
这样的事情User.test1.test2.test3.all
现在,我想要为此附加一个全局OR范围。即选择所有这些(test1 + test2 + test)或当用户是管理员时(当然不是工作代码):
scope :admin , where("OR admin=", true)
有没有办法在现有范围内执行此操作,还是需要使用AREL或纯SQL进行全新的重写?
我发现的一个黑客是:
scope :admin , where("1=1) OR admin=1 AND (1=1", true)
但是,我的意思是,这可能会变得更加丑陋......:)
答案 0 :(得分:0)
您需要使用ARel,范围始终与AND
连接。
答案 1 :(得分:0)
作为一个奇怪的黑客,我上面建议的范围确实有用。 但是,作为一个简单的解决方案,似乎最简单的方法是执行两个单独的查询并连接活动记录结果。 我使用了concat选项,我认为它也使代码可读,对性能的影响可能微乎其微(如果有的话)。
scope :test1 , where(gift: true)
scope :test2 , lambda {|time| where("last_created_at > ?", time)}
scope :test3 , where(approved: true)
scope :admin , where(admin: true)
data1 = User.test1.test2.test3.all
data2 = User.admin.all
(data1 + data2)