1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【search】gem 無し rails 検索機能 実装

Last updated at Posted at 2020-04-28

#【ゴール】
rails にて部分一致の検索機能の実装

#【開発環境】
■ Mac OS catalina
■ Ruby on Rails (5.2.4.2)
■ Virtual Box:6.1
■ Vagrant: 2.2.7

#【実装】

  1. search controllerの作作成
     ※searchアクションも同時に作成しておく
mac.terminal
$ rails g controller Search search

2.ルーティングを作成 
 ※GETメソッドで!!!!

config.routes.rb
get '/search', to: 'search#search'

2.検索フォーム用のviewファイルを作成
 ※パーシャルで作成(使い回しが効く為!!)

view.ディレクトリ内
views
 - search
  |- _form.html.erb #このファイルを新規作成
  |- search.html.erb #コントローラー作成時に同時に作成

3.検索フォームを記述
 ※GETメソッドを指定する
 ※今回は "会員" , "商品"を対象に検索
 ※"hidden_field_tag"を使用し情報だけ送付

search/_form.html.erb
<%= form_tag(search_path, method: :get) do %>
  <%= text_field_tag 'search[content]' %>
  <%= select_tag 'search[model]',options_for_select({ "会員" => "customer", "商品" => "item" }) %>
  <%= hidden_field_tag 'search[method]', "部分一致" => "partial" %>
  <%= submit_tag '検索' %>
<% end %>

  1. search controller 記述

 ※"会員"、"商品"を選んだ時を "if"で分岐
 ※凡庸性が高い、部分一致のみの検索対応

search_controller.rb

class SearchController < ApplicationController
   def search
  	@model = params["search"]["model"]
	@content = params["search"]["content"]
	@method = params["search"]["method"]
	@records = search_for(@model,@content,@method).page(params[:page]).per(5)
  end

  private
	def search_for(model,content,method)
		if model == 'customer'
		   method == 'partial'
		   Customer.where('family_name LIKE ?', '%'+content+'%')
	    else
		   method == 'partial'
		   Item.where('name LIKE ?', '%'+content+'%')
		end
	end
end

以上

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?