Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails render partial in a loop

I am new to rails and I am trying to render a partial within a loop as such.

Here , books is an array eager loaded in controller.

 books.each do |book|
   <%= render 'books/book', :book => book %>
 end

This works fine. But when the books array is really huge, it takes time for the view to load completely. Is there any other efficient way using which the same can be achieved?. I tried partial with collection(like here) as well, but even that did not make much difference in the load time of books. Any suggestions would be highly appreciated. Thanks.

like image 969
testsum Avatar asked Feb 15 '15 08:02

testsum


2 Answers

Rendering partial in a loop consume too much time because of open/close partial file every iteration. Instead of partial try to use your own helper for this purpose.

like image 125
Dima Melnik Avatar answered Oct 11 '22 03:10

Dima Melnik


If you have list of values to display in the same view then you can iterate the values in the same view instead of rendering a new partial each time. If it's not the case then it is better to pass values from controller to your view. Hope it helps.

like image 28
sansarp Avatar answered Oct 11 '22 02:10

sansarp