我有向用户显示从 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),以及如何解决这个问题。