Performance: Passing data to partials
This affects page load speed and rendering performance by controlling how much data is sent and how many partial templates are rendered.
<%= render partial: 'item', collection: @items.includes(:associated_data) %><%= render partial: 'item', collection: @items %>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Passing entire objects with all data | N partial renders | N reflows | High paint cost due to large HTML | [X] Bad |
| Passing limited, preloaded data | N partial renders | N reflows | Lower paint cost with smaller HTML | [OK] Good |
locals when rendering partials in Rails?localslocals option lets you pass data as local variables to the partial, making it flexible and dynamic.user with value @user to a partial called _profile.html.erb?locals: { key: value } inside the render call.<%= render 'profile', locals: { user: @user } %> uses locals: { user: @user } which is correct syntax. Others miss the locals hash or have wrong syntax.user = User.new(name: 'Alice')
<%= render 'user_info', locals: { user: user } %>_user_info.html.erb contains:<p>Name: <%= user.name %></p>user is passed as a local variable to the partial with value User.new(name: 'Alice').user.nameuser.name, which is 'Alice', so it renders the name correctly.<%= render partial: 'comment', locals: { comment: @comment } %>
# In _comment.html.erb
<p><%= comment_text %></p>comment: @comment, so inside the partial the variable comment is available.comment_text, which is not defined or passed, causing an undefined variable error._product.html.erb and pass each product as a local variable named item. Which code correctly renders the list with locals?render partial: 'name', collection: array, as: :var to pass each element as a local variable.<%= render partial: 'product', collection: @products, as: :item %> correctly uses partial, collection, and as: :item to pass each product as item local variable. The <% @products.each do |p| %>
<%= render 'product', locals: { item: product } %>
<% end %> uses manual loop but product is undefined (loop var is p). The <%= render partial: 'product', collection: @products, locals: { item: product } %> has wrong locals usage (product undefined). The <%= render product, collection: @products, as: :item %> misses partial keyword and unquoted product undefined.Pass the test and this pattern moves unknown