问题
In my rails 4 app I have comments for different models with polymorphic association. For the post
model I display comments on the index page
, but for product
model I do it on the show page
. I have problems with fine-tuning the rendering and caching on the post index page
, since it's comments index
in posts index
. I provided my solutions both for the post
version and product
version.
I don't use touch:true
in comment model since it doesn't make sense on the product show page. Thanks to this I don't use caching for the posts
on the posts index page
since the cache key would be too complex thanks to the comments.
My questions:
Is there a better way to render comments for the posts?
Is my caching strategy good enough or I should use an "outer" caching for product or post?
Post has_many :comments, as: :commentable
Product has_many :comments, as: :commentable
Comment belongs_to :commentable, polymorphic: true ###### NO touch: true
posts index
<%= 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 %>
products controller
def show
@product = Product.find(params[:id])
@comments = @product.comments.ordered.includes(:user, :user_profile)
end
products show
<% 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 (same both for product and post)
<% cache ['comment', comment, comment.user.profile] do %>
<%= comment.user.full_name %> #delegated from profile
<%= comment.body %>
<% end %>
来源:https://stackoverflow.com/questions/37303420/rails-rendering-index-in-index-with-fragment-caching