简体   繁体   中英

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?

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

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

您应该将片段缓存与多提取片段一起使用,这会给您带来显着的提升: https : //github.com/n8/multi_fetch_fragments (这个 gem 已经是 Rails 5 的一部分)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM