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: 皆さん、申し訳ありません。モデルの User と Profile が別の DB にあることをお知らせするのを忘れていました。

  establish_connection "accounts_#{RAILS_ENV}"

現在 - インクルード/ジョインが機能しない理由は明らかですが、アカウント データを使用して DB へのリクエストを最適化する方法をご存知でしょうか?

4

1 に答える 1

0

NewsArticle.find に :include の代わりに :joins を試してください

このリンクは参考になるかもしれません Rails :include vs. :joins

于 2010-08-12T04:14:34.083 に答える