Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails partial taking too much time to render sometimes

In my views, I am rendering a partial. This is actually a row element that shows up in a table some 500 - 600 times. I have eager loaded all associations. But, the issue is, same partial takes abruptly different render-time some times.

My rails server o/p:

Rendered admin/invoices/_update.html.erb (1330.3ms)
Rendered admin/invoices/_update.html.erb (4.8ms)
Rendered admin/invoices/_update.html.erb (4.8ms)
Rendered admin/invoices/_update.html.erb (8.8ms)
Rendered admin/invoices/_update.html.erb (4.4ms)
Rendered admin/invoices/_update.html.erb (1309.9ms)
Rendered admin/invoices/_update.html.erb (4.7ms)
Rendered admin/invoices/_update.html.erb (4.6ms)
Rendered admin/invoices/_update.html.erb (4.6ms)
Rendered admin/invoices/_update.html.erb (1322.6ms)
Rendered admin/invoices/_update.html.erb (4.2ms)

Also, there is no particular row that takes longer every time.

In my view file:

<% @updates.each do |update| %>
<%= render :partial => 'update', :locals => {:user => update[0]} #each of this is  a row %>
<% end %>

UPDATE: Also suggest if this a good way to do this? i.e: looping over a partial so many times. I can't use pagination and Ajax to fasten up things.! Any other approach.?

like image 715
Nerve Avatar asked Dec 27 '22 11:12

Nerve


2 Answers

Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection:

<%= render :partial => 'update', :collection => @updates %>

There is also a shorthand for this. Assuming @updates is a collection of update instances, you can simply write this in the index.html.erb to produce the same result:

<%= render @updates %>

Section 3.4.5 of the Rails Guides explains this in detail.

like image 141
Syed Aslam Avatar answered Jan 20 '23 04:01

Syed Aslam


Though I'm not sure why the lag spikes in the rendering, i strongly recomend inverting the order: You give all the updates to the partial and inside it you iterate and render the rows.

In view file

    <%= render :partial => 'update', :locals => {:updates => @updates} %>

And inside the update partial

    <% updates.each do |update| %>
       RENDER LOGIC
    <% end %>

This why you don't suffer the partial loading overhead for every row in your update. Hope this helps!

like image 29
CristianDonosoC Avatar answered Jan 20 '23 04:01

CristianDonosoC