2010-08-11 82 views
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,但遺憾的是它不工作:(此外,我已經試過

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 

,但沒有更新NewsArticleController改變:(

在有評論渲染NewsArticle我看到瘋狂的負載數據庫能否請你幫我優化

PS:?爭奪w是低於

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}" 

目前 - 它清楚爲什麼包含/連接不起作用,但也許你有任何想法如何優化對帳戶數據的DB請求?

+0

能否請您從您的視圖發佈的代碼? – 2010-08-11 17:04:16

+0

更新了視圖:) – 2010-08-11 20:43:55

+0

我已經更新了我的問題:)對不起,因爲缺少詳細信息:) – 2010-08-14 06:41:20

回答

0

嘗試:加入代替:在您的NewsArticle.find

此鏈接可能會有所幫助 Rails :include vs. :joins

+0

我已更新我的問題:)遺憾的遺漏細節:) – 2010-08-14 06:40:53