首页 > 解决方案 > 在范围内使用关联域进行计算

问题描述

Another有字段some_field

ThisTable belongs_to Another并且有字段local_field

现在我想写some_filter范围ThisTable

scope :some_filter, ->(var_in) {
  tmp1 = calc_sth(another.some_field, var_in)
  tmp2 = calc_sth_else(another.some_field, var_in)
  where(local_field: tmp1..tmp2)
}

我有错误undefined local variable or method 'another' for #<ActiveRecord::AssociationRelation []>

这个怎么写?

标签: ruby-on-rails

解决方案


范围不在对象的实例上执行,它们基本上是类方法。通过another在您的范围内使用,您并没有真正指出ThisTable您想要获得Another的内容。就好像你打电话一样ThisTable.another- 它不起作用。


推荐阅读