LoginSignup
0
1

More than 3 years have passed since last update.

検索フォームの設置方法

Last updated at Posted at 2021-04-23

まずは下記のようにフォームを記述。

<%= form_with(url: search_pictures_path, local: true, method: :get, class: "search-form") do |form| %>
<%= form.text_field :keyword, placeholder: "キーワードを入れてね", class: "search-input" %>
<%= form.submit "検索", class: "search-btn" %>
<% end %>

続いてルーティングを設定。
全体から検索したいのでcollectionを使う。

Rails.application.routes.draw do
  devise_for :users
  root to: "pictures#index"
  resources :pictures do
    resources :comments, only: :create
    collection do
      get 'search'
    end
  end
  resources :users, only: :show
end

次に検索のメソッドをモデルに定義。

class Picture < ApplicationRecord
  has_one_attached :image
  belongs_to :user
  has_many :comments, dependent: :destroy

  validates :image, presence: true
  validates :title, presence: true
  validates :explanation, presence: true
  validates :impression, presence: true

  def self.search(search)
    if search != ""
      Picture.where('title LIKE(?)', "%#{search}%")
    else
      Picture.all
    end
  end
end

ここで使うのはwhereメソッドとLIKE句。
whereメソッドはモデルが使用できる、ActiveRecordメソッドの1つ。
書き方は「モデル.where('検索対象となるカラムを含む条件式')」
モデル.where(条件)のように、引数部分に条件を指定することで、テーブル内の「条件に一致したレコードのインスタンス」を配列の形で取得できる。
LIKE句は、曖昧(あいまい)な文字列の検索をするときに使用するもので、whereメソッドと同時に使う。
ちなみにelse Picture.allは空で検索ボタンが押された時にずべてのデータが検索結果として表示されることを表している。

  def search
    @pictures = Picture.search(params[:keyword])
  end

続いてコントローラーにsearchアクションを記述。

次に検索結果を表示するためのビューファイルを作成。
search.html.erbファイルをviews配下のディレクトリに作成し設置。

<div class="contents row">
  <% @pictures.each do |picture| %>
    <%= render partial: "picture", locals: { picture: picture } %>
  <% end %>
</div>

検索結果がここに表示される。

これで一通りの実装が完了!

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