Is there a way to use a model´s method in my scope or in my class method?
I have these two methods on my contact class, defining if a contact is active
def active
return no_of_activities_last_year > 0 ? true : false
end
def no_of_activities_last_year
time_range = (Time.now - 1.year)..Time.now
activities.where(:updated_at => time_range).count
end
Then I would like to be able to return all active contacts by either scope or a class method, something like this:
scope :active_contacts, lambda {where(:active => true)}
or
def self.active_contacts
where(:active => true)
end
But they don´t work because the active is not part of the database.
Is there some clever way I can come by this? And preferable in a way that could be combined with other scopes?
As long as I know, there is not. The whole idea behind ActiveRecord is to make queries to the database. You cannot tell the database “get me all the records for which this ruby code logic is true”, however you can tell the database “get me all the records under this criteria”.
So you can still use a inner select for that, there may be better ways but you can do:
Its not the cleanest solution, but its fast and it will give you an idea on how to build the other queries.
If you don’t want to write raw sql and you want to do it the right way, you can always learn about Arel or use Squeel.
Alternatively, you can fetch all the data and then filter by ruby code, but that will be inefficient compared to letting the sql engine to filter the results.