我是 ActiveRecord 新查询界面的新手,所以我还在搞清楚。
scope
我希望有人能解释在 ActiveRecord 模型中使用 a 和仅使用类方法(即self.some_method
)之间的区别
据我所知,范围总是期望返回关系,而类方法不一定必须。这是真的?
例如,我认为这样做是有意义的:
class Person
scope :grouped_counts, group(:name).count
end
但这不起作用。我收到此错误:
ArgumentError: Unknown key(s): communicating, failed, matched, unmatched
from /Users/bradrobertson/.rvm/gems/ruby-1.9.2-p180@influitive/gems/activesupport-3.0.5/lib/active_support/core_ext/hash/keys.rb:43:in `assert_valid_keys'
from /Users/bradrobertson/.rvm/gems/ruby-1.9.2-p180@influitive/gems/activerecord-3.0.5/lib/active_record/relation/spawn_methods.rb:110:in `apply_finder_options'
from /Users/bradrobertson/.rvm/gems/ruby-1.9.2-p180@influitive/gems/activerecord-3.0.5/lib/active_record/named_scope.rb:110:in `block in scope'
from (irb):48
from /Users/bradrobertson/.rvm/gems/ruby-1.9.2-p180@influitive/gems/railties-3.0.5/lib/rails/commands/console.rb:44:in `start'
from /Users/bradrobertson/.rvm/gems/ruby-1.9.2-p180@influitive/gems/railties-3.0.5/lib/rails/commands/console.rb:8:in `start'
from /Users/bradrobertson/.rvm/gems/ruby-1.9.2-p180@influitive/gems/railties-3.0.5/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
r
然而,它确实作为一个类方法工作
def self.grouped_counts
group(:name).count
end
我很想知道人们对何时使用范围以及何时使用类方法的想法。我是否正确假设范围必须始终返回一个关系,但一个类方法可以返回它想要的任何东西?