rails使用片段缓存在索引中呈现索引

时间:2016-05-18 15:01:21

标签: ruby-on-rails caching rendering

在我的rails 4应用程序中,我对具有多态关联的不同模型有评论。对于post模型,我在index page上显示评论,但对于product模型,我会在show page上进行评论。我在post index page上微调渲染和缓存时遇到问题,因为它comments index中的posts index。我为post版本和product版本提供了我的解决方案。

我不会在评论模型中使用touch:true,因为它在产品展示页面上没有意义。多亏了这一点,我不会对posts上的posts index page使用缓存,因为缓存密钥因评论而过于复杂。

我的问题:

是否有更好的方式为帖子提供评论?

我的缓存策略是否足够好,或者我应该使用"外部"缓存产品或帖子?

Post has_many :comments, as: :commentable
Product has_many :comments, as: :commentable
Comment belongs_to :commentable, polymorphic: true ###### NO touch: true

发布索引

<%= render @posts %> #no caching here, key would be too complex

_post

<% cache ['post', post, post.user.profile] do %>
  <%= post.user.full_name %> #delegated from profile
  <%= post.body %>
<% end %>
<%= render partial: 'comments/form', locals: { commentable: post } %>
<%= render partial: 'comments/comment', collection: post.comments.ordered.includes(:user, :user_profile), as: :comment %>

产品控制器

def show
  @product = Product.find(params[:id])
  @comments = @product.comments.ordered.includes(:user, :user_profile)
end

产品展示

 <% cache [@product, @product.user.profile] do %>
   <%= product.user.full_name %> #delegated from profile
   <%= product.name %>
   <%= product.description %>
 <% end %>
 <% cache ['comments-index', @comments.map(&:id), @comments.map(&:updated_at).max,
   @comments.map{ |comment| comment.user.profile.updated_at }.max] %>
   <%= render @comments %>
 <% end %>

_comment(同样适用于产品和帖子)

<% cache ['comment', comment, comment.user.profile] do %>
  <%= comment.user.full_name %> #delegated from profile
  <%= comment.body %>
<% end %>

0 个答案:

没有答案