开发者

class method on active records query

开发者 https://www.devze.com 2023-03-23 10:18 出处:网络
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/combinab

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 s开发者_如何学编程elf.actives
  where("start_time >= ?", Date.today)
end

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消