0

我有向用户显示从 rss 解析的文章的页面

我的应用程序中有三个模型

class User < ActiveRecord::Base
  has_many :channels

  has_many :feed_articles, through: :channels

  has_many :comments
end

class Channel < ActiveRecord::Base  
  has_many :user

  has_many :feed_article
end

class FeedArticle < ActiveRecord::Base     
  belongs_to :channel

  has_many :comments
end

这是控制器:

  def home
    @articles = current_user.try(:feed_articles)
    @comments = current_user.comments
  end

这是视图的助手:

def take_comments_for(article)
  @comments.select{|f| f["feed_article_id"] == article.id }
end

def what_article(article)
  current_user.comments.build(feed_article_id: article.id)
end

这是视图:

- if user_signed_in?

    - @articles.each do |article|

          = link_to "#{article.title}",article.link

          = raw article.description
        - if article.favourite?

            = render :partial => "layouts/remove_from_favourite",:locals => { :article =>article }
        - else

            = render :partial => "layouts/add_to_favourite",:locals => { :article => article }
        - if take_comments_for(article).any?

            comments
          - take_comments_for(article).each do |comment|

              = comment.content
        = render :partial => "layouts/add_comment",:locals => { :article => article }

我删除了 html-tags 以获得更好的视图。

它是部分:

_add_to_favourite.html.haml(删除也是一样的。)

= form_for article, remote: true do |f|
  = f.hidden_field :favourite, :value => "true"
  = f.submit "add to favorite", class: "btn btn-primary"

_add_comment.html.haml

= form_for what_article(article) do |f|
  = f.text_area :content, :rows => 3, :class => "span6", :placeholder => 'Enter text.'
  = f.hidden_field :feed_article_id
  %br
  = f.submit "add comment", class: "btn btn-primary"

如果我启动它,我的页面每次都会为每篇文章加载渲染部分,如下所示:

 Rendered layouts/_add_to_favourite.html.haml (1.9ms)
  Rendered layouts/_add_comment.html.haml (91.7ms)
  Rendered layouts/_add_to_favourite.html.haml (1.9ms)
  Rendered layouts/_add_comment.html.haml (2.8ms)
  Rendered layouts/_add_to_favourite.html.haml (2.1ms)
  Rendered layouts/_add_comment.html.haml (2.6ms)
  Rendered layouts/_add_to_favourite.html.haml (2.1ms)
  Rendered layouts/_add_comment.html.haml (2.9ms)
  Rendered layouts/_add_to_favourite.html.haml (1.7ms)
  Rendered layouts/_add_comment.html.haml (2.6ms)
  Rendered layouts/_remove_from_favourite.html.haml (2.0ms)

页面加载时间很长。

如果我将部分添加到我的视图文件中,就可以了。

请解释一下,为什么每次都渲染(我想它需要来自控制器的变量@comments),以及如何解决这个问题。

4

1 回答 1

0

它每次都在渲染,因为您告诉它在每个块中都这样做。这本身并不是您问题的原因。

您的问题很可能与您的“take_comments_for”有关。首先,您调用它两次,一次用于 if,一次用于实际显示它。

其次,您加载关系的方式遇到了 n+1 问题。您应该设置您的关系和后续查询,以便您急切地加载评论和文章。如果为每个块中的每个单独项目点击数据库,这将在 2 个调用中预先加载所需的数据。

于 2013-09-22T02:19:20.347 回答