我是ActiveRecord新查询界面的新手,所以我还在搞清楚.
我希望有人可以解释scope在ActiveRecord模型中使用a和使用类方法之间的区别(即self.some_method)
从我可以收集的内容来看,范围总是希望返回一个关系,而一个类方法不一定必须.这是真的?
例如,我认为做以下事情是有意义的:
class Person
scope :grouped_counts, group(:name).count
end
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我收到此错误:
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
Run Code Online (Sandbox Code Playgroud)
但它确实可以作为一种类方法
def self.grouped_counts
group(:name).count
end
Run Code Online (Sandbox Code Playgroud)
我很想知道人们关于何时使用范围以及何时使用类方法的想法.我是否正确假设范围必须始终返回关系,但是类方法可以返回它想要的任何内容?
我是铁杆新手.任何人都可以告诉我有关范围.我已经通过rails指南但仍想知道它究竟是如何工作的?提前致谢.