How to chain methods with OR instead of AND ?
Closed this issue · 1 comments
cedvw commented
Very interesting gem. I have a question about the Query Builder. By default, it chains the given methods using AND, e.g:
PostQueryBuilder.new
.with_comments_by(['camertron', 'catwithtail'])
.with_title_matching("arel rocks")
.since_yesterday
Queries Post with comments AND with title AND since yesterday.
But how could I write such a builder that would allow me to make OR statements? Ideally, I would like to be able to have both AND and OR statements in a single query. Thanks.
camertron commented
Hey @cedvw, thanks for asking about this. The behavior you're observing - that AND
is used by default instead of OR
- actually comes from ActiveRecord/Arel and not from arel-helpers. The good news is that ActiveRecord supports OR
conditions in version 5 and later. Here's how you would chain two conditions together with OR
in a query builder:
class PostQueryBuilder
def initialize(query = nil)
super(query || post.unscoped)
end
def with_title_matching(title)
reflect(
query.or(
Post.where(post[:title].matches("%#{title}%"))
)
)
end
def since_yesterday
reflect(
query.or(
Post.where(post[:created_at].gteq(Date.yesterday))
)
)
end
end
I hope that helps!