daniel
daniel

Reputation: 3115

class method on active records query

Given I have a model/table with appointments, saved as a date. I want to create a method which returns me only active records. One for all records, one on an object. Is my approach improvable/combinable? Thx for advise!

def self.actives
  where("start_time >= ?", Date.today)
end

def is_active
  where("start_time >= ?", Date.today)
end

Upvotes: 1

Views: 743

Answers (1)

apneadiving
apneadiving

Reputation: 115511

Scopes are the proper way to handle your first filter. See doc: http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html

Your second filter won't work, replace with:

def is_active?
  start_time >= Date.today
end

I can't see why you want to combine both methods.

Be aware that:

  • Model.actives will provide you with an ActiveRecord Relation. You have to append .all to trigger the call. Then you'll have an array to iterate.

  • instance.is_active? will provide a boolean

Upvotes: 5

Related Questions