Corné Verbruggen
Corné Verbruggen

Reputation: 2496

DRY solution for reusing rails scope conditions in other methods?

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:

Any ideas on better solutions, that still define the conditions in one place?

Upvotes: 2

Views: 607

Answers (1)

fkreusch
fkreusch

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

Related Questions