Rails 4.1.2 Eager load不会导致N + 1查询失败

时间:2022-04-14 06:44:02

Rails: 4.1.2, Ruby: 2.1.1

Rails:4.1.2,Ruby:2.1.1

I have an Article class, which is commentable and has_many :comments

我有一个Article类,它是可评论的并且has_many:comments

module Commentable
  extend ActiveSupport::Concern

  included do
    has_many :comments, :as => :commentable
  end
end

class Comment < ActiveRecord::Base

  belongs_to :commentable, :polymorphic => true, :touch => true
  belongs_to :user

  #other codes....
end

when display the article, I'd like to load all releated information

在显示文章时,我想加载所有相关信息

@item = Article.includes(:tags, {:comments => :user}).where(id: params[:id]).first

and it does preload tags and comments object.

它确实预加载标签和评论对象。

but when I render comments, the comments object and user objects get loaded again.

但是当我渲染注释时,注释对象和用户对象再次被加载。

= render @item.comments

from log:

Rails 4.1.2 Eager load不会导致N + 1查询失败

1 个解决方案

#1


0  

Finally, I found out that Rails can’t include polymorphic associations. Calling preload still loads the related models in as few SQL statements as possible, but does not allow for querying on the related models.

最后,我发现Rails不能包含多态关联。调用preload仍会在尽可能少的SQL语句中加载相关模型,但不允许查询相关模型。

#1


0  

Finally, I found out that Rails can’t include polymorphic associations. Calling preload still loads the related models in as few SQL statements as possible, but does not allow for querying on the related models.

最后,我发现Rails不能包含多态关联。调用preload仍会在尽可能少的SQL语句中加载相关模型,但不允许查询相关模型。