我有一些模特 - 新闻文章,评论,用户(作者:作者)和简介。
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}"
目前 - 明确为什么包含/连接不起作用,但是您可能知道如何使用帐户数据优化对数据库的请求?