Created
November 29, 2017 19:03
-
-
Save anonymous/d534c7936a64759e9936e95100b54d41 to your computer and use it in GitHub Desktop.
gem を使わずにRails で LIKE OR 検索
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ArticlesController < ApplicationController | |
before_action :set_article, only: [:show, :edit, :update, :destroy] | |
def search | |
words = params[:q].split # スペース区切りでの複数単語入力を期待 | |
@articles = | |
Article.where( | |
words.size.times.map { 'body LIKE ?' }.join(' OR '), # 単語の数だけ検索条件を量産 | |
*words.map { |word| "%#{word}%" } # 各単語を曖昧検索可能な文字列に加工し引数として展開 | |
) | |
end | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment