I am in a situation to filter the records based on some conditions(conditions are in the form of scopes). in user model
scope :has_email, -> { where('email IS NOT NULL') }
scope :email_contains, (email) -> { where("email ILIKE :email'", email: email)}
If I want both conditions to be combined with 'AND' operator, We can do something like,
User.has_email.email_contains
The query generated would be
SELECT "user".* FROM "user" WHERE (email ILIKE '%gmail.com%') AND (email IS NOT NULL)
How can I proceed if I need scopes to be combined with OR operators? I found that rails 5 added support to or method(https://blog.bigbinary.com/2016/05/30/rails-5-adds-or-support-in-active-record.html), But this won't work if we use includes or joins
Eg: User.has_email.or(User.some_scope).or(User.joins(:event).temp)
How do I join scopes with OR?
The bit you are missing is that a join is forcing the association to exist. To prevent that, you use
left_joins:Still it won't solve the issue because the
.ormethod will work (by documentation) only on structurally equivalent relations.You can actually overcome it by going one step lower, to Arel:
The
where_valuesproperty is an array of Arel::Nodes::Node instances, all of which are normallyand-ed to get your query. You have toandthem by hand, and thenorthe results.If something does not work as expected, check the output of
cond.to_sqlin case you have missed something.