I am trying to perform an ActiveRecord query on my User model that uses includes to eager-load users' roles and locations. (A user has many roles and has many locations)
The Location model has a default scope. It is:
where(:status => [0, 2])
When I perform a simple query with includes, the default scope on the Location model is applied. For example, the query:
User.includes(:roles, :locations)
Will contain the following in the sql output:
SELECT "locations".*, "t0"."user_id" AS ar_association_key_name FROM "locations" INNER JOIN "locations_users" "t0" ON "locations"."id" = "t0"."location_id" WHERE "locations"."status" IN (0, 2)
However, a slightly more complex query, such as:
User.includes(:roles, :locations).where(roles: {id: 13})
Does not apply the Location default scope. Locations with a status of 1 are being included in the users' returned locations.
I notice the first query is performed with multiple SELECT statements, whereas the 2nd query is performed all as one SELECT statement with many JOINs. How can I make it so the default_scope is applied in all cases?
I am using Rails 3.2.22.