LoginSignup
0
0

More than 5 years have passed since last update.

Ransack「f.time_select」検索で空欄の場合は全ての結果を返したい

Last updated at Posted at 2016-07-05

環境

ruby 2.1.0
Rails 4.1.0
ransack 1.7.0

Ransackでf.time_select

gemRansackで開店時間を指定できる検索を実装したく、f.time_selectを用いています。
f.time_selectで時間を指定せずに検索し、空欄の場合は全ての結果が返されるようにしたいです。

現状、空欄でコンソールでの結果は
Item Load (1.5ms) SELECT DISTINCT `shops`.* FROM `shops` WHERE `shops`.`time` = '0001-01-01 00:00:00' ORDER BY `items`.`time1` ASC
となりますが0001-01-01 00:00:00のデータ無いため当然何も返されません。

結果が0001-01-01 00:00:00の場合は全てを表示というような、方法はありませんでしょうか。

item_controller.rb
def index
    @q     = Shop.ransack(params[:q])
    @q.sorts = 'name asc' if @q.sorts.empty?
    @shops = @q.result(distinct: true)
    respond_with(@shops)
end
item/index.html.erb
<h1>商品一覧</h1>

<%= search_form_for @q do |f| %>
  <%= f.label :name_cont, "商品名" %>
  <%= f.search_field :name_cont %>

  <%= f.label :city, "市町村" %>
  <%= f.search_field :shop_city_cont %>

  <%= f.label :open_time, "開店時間" %>
  <%= f.time_select :open_time_eq, :minute_step => 10, :include_blank => true %>
  <%= f.submit '検索'%>
<% end %>

<table>
  <thead>
    <tr>
      <th><%= sort_link(@q,:shop_name,'店名') %></th>
      <th><%= sort_link(@q,:shop_city, '市町村') %></th>
      <th><%= sort_link(@q,:name,'商品名') %></th>
      <th><%= sort_link(@q,:price,'値段') %></th>
      <th><%= sort_link(@q,:open_time,'開店時間') %></th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <%= render @items %>
0
0
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
0
0