Reputation: 2496
In Rails 3.1, given this model:
class Subscripion < ActiveRecord::Base
scope :active, lambda {
where("start_date is not ? AND end_date >= ?", nil, Date.today)
}
def active?
self.class.active.exists?(self)
end
end
So far, this is the dry-est solution I could think of, because it does not repeat the conditions in the active?
method.
There are two drawbacks though:
!start_date.nil? && end_date >= Date.today
. The call to exists?
results in an additional database query.exists?
on the active
scope, the result is not what we want, because exists?
ignores the instance and directly queries the database.Any ideas on better solutions, that still define the conditions in one place?
Upvotes: 2
Views: 607
Reputation: 1349
I believe the active? method implementation is not good, because it will load all active subscriptions, and then look into the list for self. A better approach would be something like this:
def active?
self.class.active.where(id: self.id).present?
end
This implementation only checks the database with a COUNT query.
In any case, I believe it would make more sense for the active? method to be with the condition you have written (!start_date.nil? && end_date >= Date.today), because it is the only way to reflect the real status of the current instance.
Upvotes: 1