我正在尝试优化数据库查询,因此在适当的地方添加了 Model.includes(:related_model)
。
在模型中的方法中使用 this 的合适方法是什么?例如,如果我的模型中有一个方法,例如:
def some_method
self.child_models.each do |child_model|
total_score += child_model.attribute
end
end
如何在这种情况下使用 includes
?这样做似乎很自然,但行不通:
def some_method
self.includes(:child_model).child_models.each do |child_model|
total_score += child_model.attribute
end
end
大多数时候,当我生成一个 n+1 查询时,我似乎在引用模型自身,但我似乎找不到任何这样的例子。
谢谢!
最佳答案
您在实例方法中使用 self,因此 self 是您的类的实例,但 includes 是一个类方法。您需要使用您的原始示例代码来使用 includes Model.includes(:related_model)
。我想你真正想要的是:
def some_method
self.child_models.sum('attribute')
end
当我在关系中构建条件而不查看实例的子项时,我会使用 include。
关于ruby-on-rails - rails 模型 : includes method on self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19235996/