1
0

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.

[Rails]検索フォームでの検索機能/複数ワードでの検索を実装する

Posted at

記事の概要

 前回の記事の続き。前回は検索フォームに入力した文字列で、あるテーブルの複数カラムを対象に検索を実行した。今回はフォームに複数のワードを入力し、AND検索できるよう実装してみたので備忘録として。検索ワードは、例えば「旅行,グルメ」のように" , "で区切るとする。

複数ワードでAND検索

app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
  def search

    # フォームから検索ワードを取得
    keywords = params[:keyword]
    
    # モデルオブジェクトを生成
    @articles = Article.all
    
    # 検索ワードの分割   
    split_keywords = keywords.split(",")

    # 分割したワードを一つずつ検索にかける
    split_keywords.each do |word|
      @articles=@articles.where(['カラム1 LIKE(?) OR カラム2 LIKE(?) OR カラム3 LIKE(?) OR カラム4 LIKE(?)',"%#{word}%", "%#{word}%", "%#{word}%", "%#{word}%"])          
    end  
  end
    
end

 

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?