0
0
RailsHow-ToBeginner · 3 min read

How to Pass Local Variables to Partial in Ruby on Rails

In Ruby on Rails, you pass local variables to a partial by using the locals option in the render method. For example, render partial: 'partial_name', locals: { variable_name: value } makes variable_name available inside the partial.
📐

Syntax

Use the render method with the partial and locals options. The partial specifies the partial file name, and locals is a hash where keys are variable names accessible inside the partial, and values are the data passed.

ruby
render partial: 'partial_name', locals: { variable_name: value }
💻

Example

This example shows how to pass a local variable greeting to a partial and display it.

erb
# In your view file (e.g., app/views/home/index.html.erb)
<%= render partial: 'greeting', locals: { greeting: 'Hello, friend!' } %>

# In the partial file (app/views/home/_greeting.html.erb)
<p><%= greeting %></p>
Output
<p>Hello, friend!</p>
⚠️

Common Pitfalls

One common mistake is forgetting to use the locals option, which means the partial won't receive the variable and will raise an error or show nothing. Another is naming the local variable differently in the partial than in the locals hash.

Also, avoid using instance variables (like @variable) inside partials if you want to keep them reusable and clear.

ruby
# Wrong way (no locals, variable undefined in partial)
<%= render partial: 'greeting' %>

# Right way
<%= render partial: 'greeting', locals: { greeting: 'Hello!' } %>
📊

Quick Reference

UsageDescription
render partial: 'name', locals: { var: value }Passes local variable var to partial _name.html.erb
render 'name', var: valueShortcut syntax to pass local variable var
In partial: <%= var %>Access the passed local variable inside the partial

Key Takeaways

Use the locals option in render to pass variables to partials.
Local variables passed are accessible by their keys inside the partial.
Always match the local variable names between render and partial.
Avoid relying on instance variables for partials to keep them reusable.
You can use shortcut syntax like render 'partial', var: value for locals.