Active Record Scope modifies Active Record Relation. Why?

67 Views Asked by At

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
2

There are 2 best solutions below

0
JT Jobe On BEST ANSWER

This appears to be an issue with Octopus, not Active Record scopes or relations.

See: https://github.com/thiagopradi/octopus/issues/455

1
lg86 On

If you default_scope than it will display on every query you make on that model. Instead use scope to avoid above problem.