0

I created an helper in my application_helper:

 def birthday(geburt)
   f = Date.today
   a = f.year - geburt.year
   a = a - 1 if (
     geburt.month >  f.month or 
    (geburt.month >= f.month and geburt.day > f.day)
    )
    a
 end 

Now i try tu use this helper in an model:

 patients = patients.where("birthday(geburtsdatum) >= ?", minimum) if minimum.present?

But how you can see in the error i somehow dont use my helper right. "geburtsdatum" is an colomn in my patients model. Thanks Error:

 SQLite3::SQLException: no such function: birthday: SELECT "patients".* FROM "patients"  WHERE (birthday(geburtsdatum) >= 15) ORDER BY vorname

My new code:

def find_patients
 patients = Patient.order(:vorname)
 patients = patients.where("nachname like ?", "%#{keyword}%") if keyword.present?
 patients = patients.where("#{geburtsdatum.get_birthday} >= ?", minimum) if   minimum.present?
 patients
end

My new error:

undefined local variable or method `geburtsdatum' for #<Search:0x4ee51b8>
John Smith
  • 6,105
  • 16
  • 58
  • 109

1 Answers1

1

Got it, then the method is for Date objects.

Including helper is doable as you mentioned in that reference but not a good practice. You can do it for a quick fix, nothing wrong.

Just for your reference, in my opinion a better approach is to extend Date class in your app to add such method and then you can call it on a Date object like some_date.process_birthday.

You can add such file in /app, or /initializers, or /lib(better but need manual require).

Then

class Date
  def get_birthday
    f = Date.today
    a = f.year - self.year
    if (self.month >  f.month) || (self.month >= f.month && self.day > f.day)
      a = a - 1
    end 
    a
  end
end
Billy Chan
  • 24,625
  • 4
  • 52
  • 68