0
0
Ruby on Railsframework~5 mins

Passing data to partials in Ruby on Rails

Choose your learning style9 modes available
Introduction

Partials help reuse small pieces of view code. Passing data to partials lets you show different content inside the same partial.

You want to show a user profile card in many pages but with different user info.
You have a list of products and want to render each product using the same layout.
You want to reuse a comment box partial but with different comments each time.
You want to pass a title or message to a shared header partial.
You want to customize a form partial with different objects.
Syntax
Ruby on Rails
<%= render partial: 'partial_name', locals: { key: value } %>
Use locals to send data as key-value pairs to the partial.
Inside the partial, use the key as a local variable to access the passed data.
Examples
Passes the @user object to the _user.html.erb partial as user.
Ruby on Rails
<%= render partial: 'user', locals: { user: @user } %>
Shortcut syntax to pass @product as product to the _product.html.erb partial.
Ruby on Rails
<%= render 'product', product: @product %>
Passes a simple string 'Hello!' as text to the _message.html.erb partial.
Ruby on Rails
<%= render partial: 'message', locals: { text: 'Hello!' } %>
Sample Program

This example shows a user profile page. The show.html.erb view renders the _user_info.html.erb partial and passes the @user object as user. The partial then displays the user's name and email.

Ruby on Rails
<!-- app/views/users/show.html.erb -->
<h1>User Profile</h1>
<%= render partial: 'user_info', locals: { user: @user } %>

<!-- app/views/users/_user_info.html.erb -->
<p>Name: <%= user.name %></p>
<p>Email: <%= user.email %></p>

<!-- app/controllers/users_controller.rb -->
class UsersController < ApplicationController
  def show
    @user = OpenStruct.new(name: 'Alice', email: 'alice@example.com')
  end
end
OutputSuccess
Important Notes

Partial names start with an underscore but you omit it when rendering.

Passing data with locals keeps partials flexible and reusable.

If you don't pass data, partials can still access instance variables from the parent view.

Summary

Partials let you reuse view code in Rails.

Use locals to pass data to partials as local variables.

This makes your views cleaner and easier to maintain.