Kumar
Kumar

Reputation: 741

Rails Render a partial inside partial with collection

I have a partial nested inside collection of partial. For example

<= render partial: "users/user", collection: @users, as: :user %>

inside _user.html.erb partial, I am rendering another partial as follow:

<%= render partial: "users/user_info", locals: {user: user}  %>

It works this way, but the problem is that it is rendering _user_info.html.erb partial for each user object and this makes it to take a long time. How can I avoid this? Any suggestions?

Upvotes: 5

Views: 4021

Answers (3)

Serhii Nadolynskyi
Serhii Nadolynskyi

Reputation: 5563

Rails will properly cache only top-level partial templates. My suggestion is to use [content_for][1] feature to move user_info partial to the top too. In your main layout:

<%= render partial: "users/user_info", collection: @users, as: :user %>
<%= render partial: "users/user", collection: @users, as: :user %>

In your 'user_info' partial:

<% content_for "user_info_#{user.id}" do %>
<!-- your user_info content -->
<% end %>

In your 'user' partial:

<!-- your user content -->
<%= content_for "user_info_#{user.id}"%>

In this case, both user_info and user partial templates will be cached properly, and rendering will take less time. [1]: https://apidock.com/rails/v3.0.0/ActionView/Helpers/CaptureHelper/content_for

Upvotes: 2

Yoni
Yoni

Reputation: 636

You should be using fragment caching along with multi fetch fragments which will give you a significant boost: https://github.com/n8/multi_fetch_fragments (This gem is already a part of Rails 5)

Upvotes: 0

Long Nguyen
Long Nguyen

Reputation: 11275

Rendering partials usually takes time. I think about 2 ways to reduce render time:

  1. Reduce partial files, which means don't use partial.
  2. Implement a proper caching strategy, in this case it's usually fragment caching.

For more information about caching strategy in Rails, take a look at: http://guides.rubyonrails.org/caching_with_rails.html#fragment-caching

Upvotes: 1

Related Questions