こんな感じで、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)