Abdul Ahmad
Abdul Ahmad

Reputation: 10021

create instance variable in erb template

Say I have 2 erb views: a list view and a show view, I want to render the show view inside the list view

list view

<% @vehicles.each do |vehicle| %>
  <h2><%= vehicle.type %></h2>
  <ul>
    <% vehicle.accessories.each do |accessory| %>
      <li><% accessory.title %></li>
    <% end %>
  </ul>
<% end %>

show view

<h2><%= @vehicle.type %></h2>
<ul>
  <% @vehicle.accessories.each do |accessory| %>
    <li><% accessory.title %></li>
  <% end %>
</ul>

the issue is the show view takes an @vehicle instance variable, how can I pass that down from the parent if I was going to nest these and it still shows up as an instance variable, accessed with @vehicle? something like:

<% @vehicles.each do |vehicle| %>
  <%= render "show" %>
<% end %>

Upvotes: 0

Views: 1470

Answers (1)

jvillian
jvillian

Reputation: 20263

I guess you might want to make that show view a partial. Something like:

<h2><%= vehicle.type %></h2>
<ul>
  <% vehicle.accessories.each do |accessory| %>
    <li><% accessory.title %></li>
  <% end %>
</ul>

Then you can do something like:

<% @vehicles.each do |vehicle| %>
  <%= render "path/to/show_partial", locals: {vehicle: vehicle} %>
<% end %>  

Naturally, you'll want to:

  • use the real path/to/show_partial, whever that happens to be, and
  • do some eager loading so that you're not doing a whole bunch of N+1 queries.

Upvotes: 2

Related Questions