Note that there are some explanatory texts on larger screens.

plurals
  1. POActiveRecord Rails 3 scope vs class method
    primarykey
    data
    text
    <p>I'm new to the new query interface of ActiveRecord so I'm still figuring things out. </p> <p>I was hoping someone could explain the difference between using a <code>scope</code> in an ActiveRecord model and just using a class method (ie <code>self.some_method</code>)</p> <p>From what I can gather, a scope is always expected to return a relation, whereas a class method doesn't necessarily have to. Is this true?</p> <p>For instance, I thought it would make sense to do something like:</p> <pre><code>class Person scope :grouped_counts, group(:name).count end </code></pre> <p>But this doesn't work. I get this error:</p> <pre><code>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 `&lt;top (required)&gt;' from script/rails:6:in `require' from script/rails:6:in `&lt;main&gt;' r </code></pre> <p>It does however work as a class method</p> <pre><code>def self.grouped_counts group(:name).count end </code></pre> <p>I'm interested to know peoples' thoughts on when to use scopes and when to use class methods. Am I correct in assuming that a scope must always return a relation, but a class method can return whatever it wants?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload