Help us understand the problem. What is going on with this article?

Rails で検索ボックスに入れるLIKE検索のScope

More than 5 years have passed since last update.

筆者環境

-

環境      バージョン 備考
MacOSX 10.9.2 MacBookProRatina
Homebrew 0.9.5
Ruby 2.1.0 最新バージョン
Rails 3.1.0,4.0.3 3系,4系ともに高負荷(月間100万PV)にて実績

-

普段、solorの全文検索を使っていますが、スコープを書いてみたので、活用してみてください。

検索条件

1.前後トリムしたい。
  例:「 テスト 」 => 「テスト」
2.スペースで値をor検索したい。
  例:「鈴木 イチロー」 => 「鈴木とイチローを検索条件にしたい。」

  scope :searchstring, ->(search_string){
    tokens = search_string.split(' ').map { |c| "%#{c.downcase}%" }
    if tokens.present?
      users = users.where((['( name like ? )']*tokens.size).join(' AND '),
                          *tokens.map { |token| [token] * 1 }.flatten)
    end
    users
  }
User.searchstring("鈴木 イチロー").to_sql
=> 
SELECT `users`.* FROM `users ` WHERE `users `.`deleted_at` IS NULL AND (( name like '%鈴木%' ) AND ( name like '%イチロー%' ))
User. searchstring("鈴 イチロー 木").to_sql
=>
SELECT `users`.* FROM `users ` WHERE `users `.`deleted_at` IS NULL AND (( name like '%鈴%' ) AND ( name like '%イチロー%' ) AND ( name like '%木%' ))

のように半角スペースで繋げた分だけLIKE検索が出来るscopeの完成!

全角スペースで繋げた場合の対策はしていないので、詳しい解説とか希望あれば書きます。

is-lab
Mobile / Tablet Web Application Development, Responsive Design, User Experience Research and Interaction Design Development, UX Strategy, UX and Agile Principles, and Experimental Execution.
https://www.vodzoo.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした