开发者

Problem with eager loading of nested models

I have some models - NewsArticle, Comment, User (as :author) and 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

As you can see - i have default_scope for Comment to eager load authors with profiles, but unfortunately it does not working :( Also i've tried to update NewsArticleController with

  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.x开发者_运维技巧ml  { render :xml => @news_article }
    end
  end

but nothing changed :(

On rendering NewsArticle with Comments i see crazy load to database. Could you please help me with optimization?

PS: view is below

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: Guys, sorry - i have forget to inform you that models User and Profile is located in another DB, that is accessed with

  establish_connection "accounts_#{RAILS_ENV}"

Currently - its clear why include/joins does not working, but maybe you have any idea how to optimize requests to DB with accounts data?


try :joins instead of :include in your NewsArticle.find

this link might be helpful Rails :include vs. :joins

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜