Rails+MySQLで日付指定

こんな感じのフォームがあったとして、年月とか日付を指定してDBから値を取ると。


画面側からわたってくるパラメータはこんなかんじ

"conditions"=>{"trails_select"=>"month", "select_year"=>"2009", "select_month"=>"7"}
"conditions"=>{"trails_select"=>"term", "to_date"=>"2009/07/31", "from_date"=>"2009/07/01"}


方法は大きく分けて、DBの型をDateでやるか文字列にするか2通りあるっぽい。

(1)Date型

SQL的にはこんなかんじ。7/23以降のレコードを取得。

 select * from hoge where created_at >= '2009-07-23';

ruby側は、パラメータからDate型を作ってあげる。
ちなみにnewするときの日に-1を指定すると、その月の最終日が取れる。
Date型そのままでもOKだけど、conditionsを(デバッグとかで出力して)
見やすいようにstrftime掛けている。
(これならDate型にしないでStringで連結の方がいいかも)

      current_year = params[:conditions][:select_year].to_i
      current_month = params[:conditions][:select_month].to_i
      from_date = Date.new(current_year, current_month,1).strftime("%Y-%m-%d")
      #日付指定だと00:00:00扱いになるので、翌月1日(00:00)未満という指定にする
      to_date = Date.new(current_year, current_month + 1,1).strftime("%Y-%m-%d")
      #最終日を指定すると含まれなくなってしまう
      #to_date = Date.new(current_year, current_month, -1).strftime("%Y-%m-%d")
      conditions = [""]
      conditions[0] += " created_at >= ? AND created_at < ?"
      conditions << from_date
      conditions << to_date

(2)文字列型

MySQLのdate_format関数を使って、DB側を文字列にする方法。

 select * from hoge where date_format(created_at,'%Y-%m-%d') >= '2009-07-23';

今回の場合は、パラメータが「2009/07/23」という形式で渡ってくるので、date_formatの方も
/区切りにしてあげる。

        to_date = params[:conditions][:to_date]
        conditions = [""]
        conditions[0] += " date_format(created_at,'%Y/%m/%d') <= ? "
        conditions << to_date

参考リンク
http://private.ceek.jp/archives/002738.html