假设有一个模型,Users
和Users
包含字段admin
(仅作为示例)。
查询必须始终返回Users
所有admin == false
,但只有在被要求时,才能返回Users
所有admin == true
,但只需一个数据库请求
所以返回子集可能是:
其中A
为admin == false
其中B
为admin == true
返回A
或A ∪ B
答案 0 :(得分:1)
这样的事情应该有效:
scope :not_admins, -> { where(admin: false) } // this is A
scope :admins, -> { where(admin: true) } // this is B
def self.example(include_admins = false)
if include_admins
self.not_admins.or(self.admins) // A U B
else
self.not_admins // A
end
end
然后您只需致电User.example()
或User.example(true)
,具体取决于您是否需要A
或A U B