简体   繁体   English

Active Record范围修改Active Record关系。 为什么?

[英]Active Record Scope modifies Active Record Relation. Why?

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. 我希望在范围上调用SQL时看起来会有所不同,但是我不明白为什么在下一次对不带范围的company_purchases调用时,范围中的其他where仍然保留。

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 这似乎是宝石章鱼的错误,请参见此处: 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 = company.purchases

# in Company model
def purchases
    Product.using(shard).where(company_id: id)
end

If you default_scope than it will display on every query you make on that model. 如果您使用default_scope ,它将显示在您对该模型进行的每个查询中。 Instead use scope to avoid above problem. 而是使用scope来避免上述问题。

This appears to be an issue with Octopus, not Active Record scopes or relations. 这似乎是八达通的问题,而不是Active Record范围或关系。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM