- 私は、今whereを使い、検索機能を実装しています。条件分岐としては、カラムが存在しない場合は、全てのカラムを表示するようにしたいと考えています。
- 現状としては、上の条件ができていない状態になっています。存在しないカラムを検索しても、カラムが何も表示されない状態になっています。空欄で検索すると、すべてのカラムが表示されます。
- 条件分岐の設定がおかしいかもしれません。(検索結果とカラムに存在するものが一致する場合は、一致したカラムを表示して、もし一致しない場合は、全部のカラムを表示するようにしたい)
- もしわかる方がいらしたら、教えていただくと幸いです。
controller/plans_controller.rb
1 if params[:title].present? 2 @plans = Plan.where(['title LIKE ?', "%#{params[:title]}%"]).page(params[:page]).per(5).order("created_at DESC") 3 else 4 @plans = Plan.includes(:guider).page(params[:page]).per(5).order("created_at DESC") 5 end
views/index.html.erb
1 <div class="middle-container"> 2 <div class="search"> 3 <%= form_tag plans_path, :method => 'get', :class => 'search' do %> 4 <p class="search_answer"><%= text_field_tag "title", "", class: "question" %> 5 <%= submit_tag "Search", :name => nil, class: "answer" %></p> 6 <% end %> 7 </div> 8 </div>
model/plan.rb
1 belongs_to :guider 2 belongs_to :home
sql文
1 Started GET "/search" for ::1 at 2019-04-21 12:09:27 +0300 2Processing by HomeController#search as HTML 3 Rendered home/search.html.erb (180.8ms) 4Completed 200 OK in 184ms (Views: 183.1ms | ActiveRecord: 0.0ms) 5 6 7Started GET "/plans?utf8=%E2%9C%93&title=kobe" for ::1 at 2019-04-21 12:09:37 +0300 8Processing by PlansController#index as HTML 9 Parameters: {"utf8"=>"✓", "title"=>"kobe"} 10 Plan Load (21.8ms) SELECT `plans`.* FROM `plans` WHERE (title LIKE '%kobe%') ORDER BY created_at DESC LIMIT 5 OFFSET 0 11 Guider Load (5.1ms) SELECT `guiders`.* FROM `guiders` WHERE `guiders`.`id` = 1 LIMIT 1 12 Rendered plans/index.html.erb within layouts/application (156.9ms) 13Completed 200 OK in 400ms (Views: 323.3ms | ActiveRecord: 40.7ms) 14 15 16Started GET "/plans?utf8=%E2%9C%93&title=kobe" for ::1 at 2019-04-21 12:09:38 +0300 17Processing by PlansController#index as HTML 18 Parameters: {"utf8"=>"✓", "title"=>"kobe"} 19 Plan Load (0.8ms) SELECT `plans`.* FROM `plans` WHERE (title LIKE '%kobe%') ORDER BY created_at DESC LIMIT 5 OFFSET 0 20 Guider Load (0.9ms) SELECT `guiders`.* FROM `guiders` WHERE `guiders`.`id` = 1 LIMIT 1 21 Rendered plans/index.html.erb within layouts/application (16.0ms) 22Completed 200 OK in 251ms (Views: 248.2ms | ActiveRecord: 1.7ms)
回答1件
あなたの回答
tips
プレビュー