ruby-on-rails - 如何预先加载嵌套的多态关联

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

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

这是我的模型设置:

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

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

最佳答案

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

    class Post
      has_many :comments, as: :ownable
    end

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

这里发布了一个工作Eager load polymorphic

关于ruby-on-rails - 如何预先加载嵌套的多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19290251/

相关文章:

sql - 联接表记录不存在的Active Record

ruby-on-rails - Restangular POST 不传递数据参数

ruby - 重定向到 @timecard 结果为 'no route matches [PATCH] "/timecards"

ruby-on-rails - Rails不会替换database.yml中的ENV值

php - 提取表中与 Codeigniter Active Record 具有相同值的记录计数

ruby-on-rails - 详细说明 MVC 如何在 Rails 中工作,以及 Controller 如何与表单等通信?

ruby-on-rails - 使用 ActiveRecord 和 Postgres 分组

javascript - rails 4 : select DOM element with dynamically generated id

ruby-on-rails - 为什么 Ruby on Rails 操作 "destroy"没有命名为 "delete"?

ruby-on-rails - 启动 Rails 脚手架时出现 OSX Ruby 错误 : Could not load OpenSSL