LoginSignup
12
12

More than 5 years have passed since last update.

Postモデルから、search_wordsに含まれる単語をAND検索する

Last updated at Posted at 2015-01-22

こんな感じで、scopeを用意してみる

post.rb
  scope :search, ->(search_words) {
    return if search_words.empty?
    post_arel = Post.arel_table[:content]
    conditions = search_words.map { |word| post_arel.matches("%#{word}%") }
    where_clauses = conditions.inject do |arel_cond, condition|
      arel_cond.and(condition)
    end
    where(where_clauses)
  }

ORの場合はこんな感じ

-     arel_cond.and(condition)
+     arel_cond.or(condition)
12
12
1

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
12
12