Rails 5 - Use limit on ActiveRecords with OR
Rails 5 comes released a new ActiveRecord or
but it still have some constraints you should know.
limit
, offset
, distinct
should be on both queries, otherwise:
irb(main):001:0> Session.where(user_id: 1).or(
Session.where(provider: 'github').limit(10)
).to_sql
=> ArgumentError: Relation passed to #or must be structurally compatible.
Incompatible values: [:limit]
You need to add limit
to both sides of the query, like:
irb(main):002:0> puts Session.where(user_id: 1).limit(10).or(
Session.where(provider: 'github').limit(10)
).to_sql
=> "SELECT "sessions".*
FROM "sessions"
WHERE ("sessions"."user_id" = 1 OR "sessions"."provider" = 'github')
LIMIT 10"
Tweet