0

我有一些模型 - 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}"

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

4

1 回答 1

0

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

这个链接可能有帮助 Rails :include vs. :joins

于 2010-08-12T04:14:34.083 回答