0

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 

今、モデルでこのヘルパーを使用してみます:

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

しかし、エラーでどのように確認できるか、ヘルパーを正しく使用していません。「geburtsdatum」は、私の患者モデルの列です。エラー:

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

私の新しいコード:

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

私の新しいエラー:

undefined local variable or method `geburtsdatum' for #<Search:0x4ee51b8>
4

1 に答える 1

1

わかりました、メソッドは Date オブジェクト用です。

そのリファレンスで述べたようにヘルパーを含めることは可能ですが、良い習慣ではありません。迅速な修正のためにそれを行うことができます。何も問題はありません。

参考までに、私の意見では、アプリの Date クラスを拡張してそのようなメソッドを追加し、 のような Date オブジェクトでそれを呼び出すことをお勧めしますsome_date.process_birthday

そのようなファイルを/app、 または/initializers、または/lib(より良いが手動で必要) に追加できます。

それで

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
于 2013-09-14T12:58:50.150 に答える