LoginSignup
9
5

More than 3 years have passed since last update.

gemのransackで複数カラムを検索対象にする方法

Posted at

始めに

僕自身複数カラムを検索対象にするのは難しいと思っていたのですが、思っていたより簡単にできたので是非参考にしてもらえたらなと思い、書くことにしました。

前提

僕はPostモデルのtitleとdescriptionを検索対象にやっていきます。

class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|
      t.string :title  ⬅️⬅️⬅️⬅️⬅️⬅️これ
      t.integer :recommended    
      t.text :description ⬅️⬅️⬅️⬅️これ
      t.references :user, foreign_key: true

      t.timestamps
    end
    add_index :posts, [:user_id, :created_at]
  end
end

やり方

始めにviewの一部を変えていきます。
titleだけを検索対象の場合は、

<%= f.search_field :title_cont, placeholder: "キーワード検索", class: 'form-control font-awesome' %>

titleとdescriptionの複数を検索対象にする場合、

<%= f.search_field :title_or_description_cont, placeholder: "キーワード検索", class: 'form-control font-awesome' %>

比較すると、titleだけ検索対象の方はtitle_contなのに対し、複数検索対象の方はtitle_or_description_contとなっています。orを入れるだけです!

次はcontrollerです。
僕の場合、titleだけ検索対象だと、

def set_search
  if logged_in?
    @search_word = params[:q][:title_cont] if params[:q]
    @q = current_user.feed.page(params[:page]).per(10).ransack(params[:q])
    @feed_items = current_user.feed.page(params[:page]).per(10)
    @posts = @q.result(distinct: true)
  end
end

複数検索対象だと、ここも先ほどのviewと一緒で一部変更するだけです!

@search_word = params[:q][:title_or_description_cont] if params[:q]

これで複数カラムを検索対象にできました!!!

9
5
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
9
5