I have encountered some unexpected behavior in Active Record (3.2.13):
There is a simple scope on my model:
class User < ActiveRecord::Base
scope :verified, lambda { where('verified = 1') }
end
This can be used fine on its own:
User.verified.to_sql
#=> "SELECT \"users\".* FROM \"users\" WHERE (verified = 1)"
When I concatenate where
-clauses, they are and
ed as expected:
User.where(company_id: 1).where(company_id: 2).to_sql
"SELECT \"users\".* FROM \"users\" WHERE \"users\".\"company_id\" = 1 AND \"users\".\"company_id\" = 2"
Problem:
However, when I chain a scope, my first where-clause is nuked, the last one wins in a merge:
User.where(company_id: 1).where(company_id: 2).verified.to_sql
"SELECT \"users\".* FROM \"users\" WHERE \"users\".\"company_id\" = 2 AND (verified = 1)"
How to apply a scope on a relation with existing conditions?
(Those existing conditions have been established through cancan's load_and_authorize_resource
so I cannot just apply those where
clauses after applying my scope.)