Given the following partial _user.html.erb and its usage, what will be rendered?
<!-- _user.html.erb -->
<p>User: <%= user.name %></p>
<!-- In a view -->
<%= render partial: 'user', locals: { user: OpenStruct.new(name: 'Alice') } %>
Remember that locals passes variables to partials as local variables.
The partial receives user as a local variable with the value OpenStruct.new(name: 'Alice'). So user.name outputs 'Alice'.
You want to render a list of @products using the _product.html.erb partial. Which code correctly passes the collection?
Use the collection: option to render a partial for each item.
Option C uses collection: which renders the partial once per item in @products, assigning each item to product local variable.
Consider this partial and its render call:
<!-- _item.html.erb -->
<p>Item: <%= item.title %></p>
<!-- In a view -->
<%= render partial: 'item' %>
Why does this raise an error?
Check what variables the partial uses and what is passed in the render call.
The partial uses item but the render call does not pass any local variable named item. This causes a NameError.
Given these partials and render calls:
<!-- _comment.html.erb -->
<p>Comment: <%= comment.text %></p>
<!-- _post.html.erb -->
<h2><%= post.title %></h2>
<%= render partial: 'comment', collection: post.comments %>
<!-- In a view -->
<%= render partial: 'post', locals: { post: OpenStruct.new(title: 'Hello', comments: [OpenStruct.new(text: 'Nice!'), OpenStruct.new(text: 'Great!')]) } %>
What will be rendered?
Remember that collection: passes each item as a local variable named after the partial.
The post partial renders the comment partial twice, once for each comment, passing each comment as comment local variable.
Choose the most accurate description of how locals work when rendering partials in Rails.
Think about variable scope and how data is shared with partials.
Locals are explicitly passed variables to partials and exist only within that partial's scope. They do not affect global or instance variables.