我是新來的ActiveRecord的新查詢接口,所以我仍然搞清楚事情。ActiveRecord Rails 3範圍vs類方法
我希望有人能解釋ActiveRecord模型使用scope
和只使用一個類的方法之間的差異(即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/[email protected]/gems/activesupport-3.0.5/lib/active_support/core_ext/hash/keys.rb:43:in `assert_valid_keys'
from /Users/bradrobertson/.rvm/gems/[email protected]/gems/activerecord-3.0.5/lib/active_record/relation/spawn_methods.rb:110:in `apply_finder_options'
from /Users/bradrobertson/.rvm/gems/[email protected]/gems/activerecord-3.0.5/lib/active_record/named_scope.rb:110:in `block in scope'
from (irb):48
from /Users/bradrobertson/.rvm/gems/[email protected]/gems/railties-3.0.5/lib/rails/commands/console.rb:44:in `start'
from /Users/bradrobertson/.rvm/gems/[email protected]/gems/railties-3.0.5/lib/rails/commands/console.rb:8:in `start'
from /Users/bradrobertson/.rvm/gems/[email protected]/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
我想知道人民在何時使用範圍的想法以及何時使用類方法的工作。我認爲範圍必須總是返回一個關係,但是一個類方法可以返回任何想要的結果嗎?
酷,thx爲輸入! – brad 2011-05-05 15:46:24
優秀的答案。也看到這篇文章:[命名的範圍已經死了](http://www.railway。at/2010/03/09/named-scopes-are-dead /) – mjnissim 2013-02-09 19:50:32