David Lilue
David Lilue

Reputation: 631

Define ActiveRecord method to work with different ActiveRecord Relations in Ruby on Rails

Let say that we have a method in a

class MyModel < ActiveRecord::Base
    def self.stats
        # do something and returns a hash
    end
end

The method needs to iterate over the records and possibly call each.

I want to use this method with scopes, where, all, etc. Like following:

MyModel.all.stats
#=> one hash
MyModel.where("created_at > ?", 1.day.ago).stats
#=> another hash
MyModel.funny.stats
#=> funny hash
...

Is this possible? I need to pass the ActiveRecord Relation as a parameter or the scopes as parameters?

Upvotes: 2

Views: 114

Answers (1)

Rodrigo
Rodrigo

Reputation: 4802

Yes, the scope inside the stats method will be the Relation

def self.stats
  count
end

MyModel.all.stats 
# => 10
MyModel.where("created_at > ?", 1.day.ago).stats
# => 5

Here is a good resource http://blog.plataformatec.com.br/2013/02/active-record-scopes-vs-class-methods/

If you want to iterate over the records, you could use the find_each method:

def self.stats
  find_each do |my_model|
    puts my_model.id
  end
end

Upvotes: 1

Related Questions