LoginSignup
5
6

More than 5 years have passed since last update.

Heroku で ransack による日付一致検索

Last updated at Posted at 2015-03-06

概要

gem 'ransack' で検索機能を追加。
日付一致検索に関しては、エラーが起きていたので、ransacker で日付用のメソッドを作成。

Ruby 2.1.5
Rails 4.2.0
ransack 1.6.3

編集すべきファイル

  • config/initializers/ransack.rb を作成し、日付に変換して比較するメソッド追加
config/initializers/ransack.rb
Ransack.configure do |config|
  config.add_predicate 'date_equals',
  arel_predicate: 'eq',
  formatter: proc { |v| v.to_date },
  formatter: proc { |v| v.present? },
  type: :string
end
  • 日付検索を追加したい modelransacker を追加
app/model/purchase.rb
private 
  ransacker :order_date do
    Arel.sql('date(order_date)')
  end
  • 日付検索を追加したい view app/purchases/search.html.erb へ先ほど作ったメソッドを追加
app/views/purchases/search.html.erb
<label>注文日</label>
<%= f.search_field :order_date_date_equals, class: 'date' %>
  • controller の ストロングパラメーターに追加
app/controller/purchase_controller.rb
class PurchaseController < ApplicationController
  private
  def search_params
    search_conditions = %i(
      order_date_date_equals
    )
    params.require(:q).permit(search_conditions)
  end
end

参考にしたサイト

背景

ローカルのSQLite3では、問題なく動いていたのに、
herokuに上げたら、以下のエラーで止まってしまった。

postgresql用に、date型を指定してeqで比較する。

heroku logs

app[web.1]: Parameters: {"utf8"=>"✓", "q"=>{"order_date_cont"=>"2015-03-02"}}
app[web.1]: Purchase Load (4.9ms)  SELECT DISTINCT "purchases".* FROM "purchases" WHERE ("purchases"."order_date" ILIKE '%2015-03-02%')  ORDER BY "purchases"."order_date" DESC
app[web.1]: PG::UndefinedFunction: ERROR:  operator does not exist: date ~~* unknown
app[web.1]: LINE 1: ... FROM "purchases" WHERE ("purchases"."order_date" ILIKE '%20...
app[web.1]:                                                              ^
app[web.1]: HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
app[web.1]: SELECT DISTINCT "purchases".* FROM "purchases" WHERE ("purchases"."order_date" ILIKE '%2015-03-02%')  ORDER BY "purchases"."order_date" DESC
app[web.1]: Rendered shared/_search_result_box.html.erb(6.9ms)
app[web.1]: Completed 500 Internal Server Error in 69ms
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6