新手问题 has_many 传了 scope 参数后,includes 会报错,如何解决

ad583255925 · 2017年03月14日 · 最后由 mengqing 回复于 2017年03月14日 · 1521 次阅读

ArgumentError: The association scope 'children' is instance dependent (the scope block takes an argument). Preloading instance dependent scopes is not supported.

def check_preloadable!
     return unless scope

     if scope.arity > 0
       raise ArgumentError, <<-MSG.squish
         The association scope '#{name}' is instance dependent (the scope
         block takes an argument). Preloading instance dependent scopes is
         not supported.
       MSG
     end
   end
   ...

这个是源码

需求是一张表通过 parent_id 关联自己 (has_many: children),但是还要加一个条件

class Cm::ProductCategory < ApplicationRecord
has_many :children, ->(p) {where(version_id: p.version_id)}, class_name: 'Cm::ProductCategory', primary_key: :product_category_id, foreign_key: :parent_id
...

这样写,includes 就报错

这个在 4.2 的时候就被 deprecated 了,然后应该是 5.0 的时候被移除了。

你可以试试https://github.com/rails/rails/issues/23435里的方法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号