ruby-on-railsactiverecordactivemodel

Rails custom model method in where query


In my rails app I have defined in the Kid model a calculation based on the fields from the Kids DB. the method is as follows:

def flip_date 
  self.dob.advance(months: 10) 
end

I want to use this in my controller as I have a method where I am defining something as follows:

new_kids = Kid.where(discharge_date: nil).where('flip_date > ?', Date.current.advance(year: 1).beginning_of_year)

However I keep getting the following error:

SQLite3::SQLException: no such column: flip_date: SELECT "kids".* FROM "kids" WHERE "kids"."discharge_date" IS NULL AND (flip_date < '2017-01-01')

Any ideas on how can I make this work? All help is appreciated!


Solution

  • If you really want to use model methods take a look at http://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/select

    For your case:

    new_kids = Kid.where(discharge_date: nil).select{|k| k.flip_date > Date.current.advance(year: 1).beginning_of_year}
    

    But select method takes every object in memory before returning final result. Hence I will advise to use normal where clause and instead of flip_date take dob (which is a column in database) in consideration.

    Like this

    new_kids = Kid.where(discharge_date: nil).where('dob > ?', <date criteria>)