Reusing Rails scopes in the OR operator
Ruby on Rails allows to use OR
operator while building ActiveRecord queries:
User.where(id: 1).or(User.where(status: 'active'))
Since OR
operator requires both relations to be structurally compatibly, it might get tedious with multiple conditionals and joins:
User
.joins(:account)
.where(accounts: { status: 'active' })
.or(User.joins(:account).where.not(name: nil))
(even though accounts
association is not used in the or
condition, it needs to be included to remain structural compatibility)
ActiveRecord::Relation#scoping can help with scoping all queries in within the block:
User.joins(:account).scoping do
User.where(accounts: { status: 'active' }).or(User.where.not(name: nil))
end
If above code is within User
model, it can even gets simpler:
joins(:account).scoping do
where(accounts: { status: 'active' }).or(where.not(name: nil))
end