Applying a scope to a an Active Record Relation is permanently modifying the relation. Why?
company_purchases.to_sql
=> "SELECT \"purchases\".* FROM \"purchases\" WHERE \"purchases\".\"company_id\" = 17"
company_purchases.by_state("finalized").to_sql
=> "SELECT \"purchases\".* FROM \"purchases\" WHERE \"purchases\".\"company_id\" = 17 AND \"purchases\".\"state\" = 'finalized'"
company_purchases.to_sql
=> "SELECT \"purchases\".* FROM \"purchases\" WHERE \"purchases\".\"company_id\" = 17 AND \"purchases\".\"state\" = 'finalized'"
I expect the SQL to look different when called on the scope, but I don't understand why the additional where from the scope remains on the next call to company_purchases without the scope.
The scope definition
scope :by_state, ->(state) { where(state: state) }
UPDATE
This appears to be a bug with the gem Octopus, see here: https://github.com/thiagopradi/octopus/issues/455
For additional context, the Octopus bug is being introduced because of how company_purchases is composed.
company_purchases = company.purchases
# in Company model
def purchases
Product.using(shard).where(company_id: id)
end
This appears to be an issue with Octopus, not Active Record scopes or relations.
See: https://github.com/thiagopradi/octopus/issues/455