【问题标题】:How to eager load a nested polymorphic association如何急切加载嵌套的多态关联
【发布时间】:2013-10-17 21:18:08
【问题描述】:

我正在尝试加载嵌套的多态关联。我似乎找不到解决方案。

这是我的模型设置:

class Post
  has_many :comments
end

class Comment
  belongs_to :ownable, polymorphic: true
end

class User
  has_many :comments, as: :ownable
end

这就是我想要做的:

Post.includes(comments: :ownable).to_a

但它抛出了这个错误:

ActiveRecord::EagerLoadPolymorphicError - Can not eagerly load the polymorphic association :ownable

我怎样才能预先加载这个嵌套的多态关联?

【问题讨论】:

标签: ruby-on-rails activerecord ruby-on-rails-4 eager-loading


【解决方案1】:

首先你的帖子 has_many cmets 也应该设置为 :as => ownable

    class Post
      has_many :comments, as: :ownable
    end

即使在更改此设置后,您仍然会收到相同的错误,因为 rails 找不到可拥有的表。

这里有一个解决办法Eager load polymorphic

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    相关资源
    最近更新 更多