Проблема со стремительной загрузкой вложенных моделей - PullRequest
0 голосов
/ 11 августа 2010

У меня есть несколько моделей - NewsAr Article, 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 для Comment, чтобы загружать авторов с профилями, но, к сожалению, этоне работает :( Также я пытался обновить 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 находятся в другой БД, доступ к которой осуществляется с помощью

  establish_connection "accounts_#{RAILS_ENV}"

В настоящее время понятно, почему include / joins не работает, но, возможно, у вас есть идея оптимизировать запросы к БД с данными учетных записей?

1 Ответ

0 голосов
/ 12 августа 2010

try: join вместо: include в вашем NewsArticle.find

эта ссылка может быть полезной Rails: include vs.: joins

...