【问题标题】:Problem with eager loading of nested models急切加载嵌套模型的问题
【发布时间】:2010-08-11 16:25:22
【问题描述】:

我有一些模型 - NewsArticle、Comment、User (as :author) 和 Profile。

class NewsArticle < ActiveRecord::Base
  belongs_to :author, :class_name => "User", :foreign_key => "user_id"
  has_many :comments, :as => :commentable, :dependent => :destroy, :order => 'created_at', :include => 'translations'
end

class Comment < ActiveRecord::Base
  belongs_to :author, :class_name => "User", :foreign_key => "user_id"
  belongs_to :commentable, :polymorphic => true, :counter_cache => true

  default_scope :include => [{:author => :profile}, :translations]
end

class User < ActiveRecord::Base
  has_one :profile
  accepts_nested_attributes_for :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

如您所见 - 我有 default_scope 用于评论以急切加载作者的个人资料,但不幸的是它不起作用:(我还尝试使用更新 NewsArticleController

  def show
    @news_article = NewsArticle.find(params[:id], :include => {:comments => {:author => :profile}})
    @comments = @news_article.comments(:order => "created_at DESC")

    respond_to do |format|
      format.html
      format.xml  { render :xml => @news_article }
    end
  end

但没有任何改变:(

在渲染带有评论的 NewsArticle 时,我看到数据库的负载很疯狂。你能帮我优化一下吗?

PS:下面是视图

news_articles/show.html.haml

.comments
  %h2
    %a{:id => 'comments', :name => 'comments'}
      - if @news_article.comments_count == 0
        No comments
      - else
        #{pluralize(@news_article.comments_count, I18n.t(:"global.words.comment"))}

  %ul
    - @comments.each do |comment|
      = render :partial => "comment", :object => comment, :locals => {:source => source}

news_articles/_comment.html.haml

%li.comment.white-box
  .title
    %acronym{ :title => "#{comment.created_at.strftime(formatted_datetime)}"}
      = comment.created_at.strftime(formatted_datetime)
    %p
      = I18n.t(:"global.words.by")
      %a{ :href => "#" }
        = link_to_author_of comment

  .text
    :cbmarkdown
      #{comment.body}

  %br/
  .controls
    = link_to I18n.t(:"flags.controls.flag"), flag_comment_path(comment, :source => source), :class => 'flag-link', :rel => 'nofollow'
    = link_to I18n.t(:"comments.controls.destroy"), comment_path(comment, :source => source), :confirm => I18n.t(:"global.messages.are_you_sure"), :method => :delete

PPS:伙计们,对不起 - 我忘记告诉你模型用户和个人资料位于另一个数据库中,可以通过

访问
  establish_connection "accounts_#{RAILS_ENV}"

目前 - 很清楚为什么 include/joins 不起作用,但也许您知道如何使用帐户数据优化对 DB 的请求?

【问题讨论】:

  • 能否请您发布您认为的代码?
  • 我已经更新了我的问题 :) 抱歉缺少细节 :)

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


【解决方案1】:

尝试 :joins 而不是 :include 在您的 NewsArticle.find 中

此链接可能会有所帮助 Rails :include vs. :joins

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2019-07-30
    • 2019-05-19
    相关资源
    最近更新 更多