Today I Learned

hashrocket A Hashrocket project

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"
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.