LoginSignup
2
0

More than 1 year has passed since last update.

MySQLで稼働するRuby on Rails で Ransack を使った全文検索(fulltext search)の実装

Last updated at Posted at 2023-03-09

やりたいこと

会社 Corporation を会社名 name というフィールドで全文検索したい

やるべきこと

1.全文検索インデックスを貼る

db/migrate/00000000000000_add_index_to_corporations.rb
class AddIndexToCorporations < ActiveRecord::Migration[7.0]
  def up
    execute 'CREATE FULLTEXT INDEX `index_corporations_on_name` ON corporations  (name) WITH PARSER ngram'
  end

  def down
    execute 'ALTER TABLE corporations DROP INDEX `index_corporations_on_name`'
  end
end

WITH PARSER ngramを指定する必要があるのでadd_index :corporations, :name, type: :fulltextではダメです。

2. Ransackの条件を定義します

下記のようにname_contを検索条件としています。

        = search_form_for @query, url: search_corporations_path do |f|
          = f.input :name_cont, label: false,placeholder: '社名で検索'

以下のようにモデルにScopeを追加してransackable_scopesを使いRansackに渡してください。

models/corporation.rb
  scope :name_cont, ->(name) { where('match (`name`) against (?)', name) }

  def self.ransackable_scopes(_auth_object = nil)
    %i[name_cont]
  end
2
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
2
0