Rails return 模型子集,a = 始终为 false,a = true 有时
Rails return model subsets, a = false always, a = true sometimes
假设有一个模型,Users
并且 Users
有字段 admin
(只是一个例子)。
查询必须始终 return all Users
where admin == false
但仅当被要求这样做时,也 return all Users
where admin == true
,但在一个数据库请求中。
所以 return 个子集可能是:
其中 A
是 admin == false
其中 B
是 admin == true
Return A
或 A ∪ B
像这样的东西应该可以工作:
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
假设有一个模型,Users
并且 Users
有字段 admin
(只是一个例子)。
查询必须始终 return all Users
where admin == false
但仅当被要求这样做时,也 return all Users
where admin == true
,但在一个数据库请求中。
所以 return 个子集可能是:
其中 A
是 admin == false
其中 B
是 admin == true
Return A
或 A ∪ B
像这样的东西应该可以工作:
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