Skip to content

Instantly share code, notes, and snippets.

Created November 29, 2017 19:03
Show Gist options
  • Save anonymous/d534c7936a64759e9936e95100b54d41 to your computer and use it in GitHub Desktop.
Save anonymous/d534c7936a64759e9936e95100b54d41 to your computer and use it in GitHub Desktop.
gem を使わずにRails で LIKE OR 検索
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