Rails 在内部将范围转换为类方法那么为什么我们不能使用类方法本身而不是使用范围。
最佳答案
来自fine guide :
14 Scopes
[...]
To define a simple scope, we use thescopemethod inside the class, passing the query that we'd like to run when this scope is called:class Article < ActiveRecord::Base scope :published, -> { where(published: true) } endThis is exactly the same as defining a class method, and which you use is a matter of personal preference:
class Article < ActiveRecord::Base def self.published where(published: true) end end
特别注意:
This is exactly the same as defining a class method, and which you use is a matter of personal preference
还有一个 little further (顺便说一句,Rails3 指南在这里说了同样的话):
14.1 Passing in arguments
[...]
Using a class method is the preferred way to accept arguments for scopes.
所以你使用哪个是一个偏好问题,甚至建议你对带参数的范围使用类方法。
使用 scope 主要是一个符号问题。如果你说 scope :whatever 那么你明确地说 whatever 是一个查询构建器;如果你说 def self.whatever 那么你并没有暗示任何关于 whatever 方法的意图,你只是定义了一些可能行为也可能不行为的类方法就像一个范围。
当然,14.1 通过建议您在作用域接受参数时不要使用 scope 来混淆这种符号区分。还要记住,在 Rails3 中你可以说:
scope :published, where(published: true)
因此无参数范围在视觉上是“干净”和简洁的,但是添加一个 lambda 来处理参数会使它看起来更困惑:
scope :pancakes, ->(x) { where(things: x) }
但 Rails4 想要 lambda,即使是对于无参数范围,这种区别现在更没有意义了。
我怀疑此时的差异是历史性的。作用域在过去可能是一种特殊的东西,但在 Rails3 时代变成了普通的旧类方法,以减少重复并更好地与 Rails3 附带的新查询接口(interface)相结合。
因此,如果您愿意,可以跳过scope 并直接进入类方法。当您的范围接受参数时,您甚至会被鼓励这样做。
关于ruby-on-rails - Ruby on Rails ActiveRecord 范围与类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32930312/