是否可以否定 Rails 3 中的范围? [英] Is it possible to negate a scope in Rails 3?
问题描述
我的类具有以下范围,称为 Collection
:
I have the following scope for my class called Collection
:
scope :with_missing_coins, joins(:coins).where("coins.is_missing = ?", true)
我可以运行 Collection.with_missing_coins.count
并返回结果——效果很好!目前,如果我想在不丢失硬币的情况下获得收藏,我会添加另一个范围:
I can run Collection.with_missing_coins.count
and get a result back -- it works great!
Currently, if I want to get collections without missing coins, I add another scope:
scope :without_missing_coins, joins(:coins).where("coins.is_missing = ?", false)
我发现自己写了很多这些相反"的范围.是否有可能在不牺牲可读性或诉诸 lambda/方法(以 true
或 false
作为参数)的情况下获得作用域的反面?
I find myself writing a lot of these "opposite" scopes. Is it possible to get the opposite of a scope without sacrificing readability or resorting to a lambda/method (that takes true
or false
as a parameter)?
像这样:
Collection.!with_missing_coins
推荐答案
我不会为此使用单一作用域,而是使用两个作用域:
I wouldn't use a single scope for this, but two:
scope :with_missing_coins, joins(:coins).where("coins.is_missing = ?", true)
scope :without_missing_coins, joins(:coins).where("coins.is_missing = ?", false)
这样,当使用这些作用域时,就会清楚地知道发生了什么.根据 numbers1311407 的建议,尚不清楚 with_missing_coins
的 false
参数在做什么.
That way, when these scopes are used then it's explicit what's happening. With what numbers1311407 suggests, it is not immediately clear what the false
argument to with_missing_coins
is doing.
我们应该尽量写出尽可能清晰的代码,如果这意味着不那么热衷于 DRY,那么就这样吧.
We should try to write code as clear as possible and if that means being less of a zealot about DRY once in while then so be it.
这篇关于是否可以否定 Rails 3 中的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!