Victor
Victor

Reputation: 13378

How to iterate instance variables within instance variables in view?

I'm using Rails 3.2. I have the following code:

# transports_controller.rb
@transports = %w(car bike)

@transports.each do |transport|
  instance_variable_set("@#{transport.pluralize}", 
                        transport.classify.constantize.all)
end

# transports/index.html.erb
<% @transports.each do |transport| %>
  <h1><%= transport.pluralize.titleize %></h1>
  <% @transport.pluralize.each do |transport_item| %>
    <%= transport_item.name %><br>
  <% end %>
<% end %>

The controller code is correct, but the view code is wrong. @transport.pluralize.each cannot be called literally . Expected result is:

<h1>Cars</h1>
Ferrari<br>
Ford<br>

<h1>Bikes</h1>
Kawasaki<br>
Ducati<br>

How do I do this?

Upvotes: 0

Views: 137

Answers (2)

Stefan
Stefan

Reputation: 114178

You don't have to create instance variables for this, just use an array (or a hash):

transport_classes = [Car, Bike]

@transports = transport_classes.map { |transport_class|
  [transport_class, transport_class.all]
}
# this returns a nested array:
# [
#   [Car, [#<Car id:1>, #<Car id:2>]],
#   [Bike, [#<Bike id:1>, #<Bike id:2>]
# ]

In your view:

<% @transports.each do |transport_class, transport_items| %>
  <h1><%= transport_class.to_s.pluralize.titleize %></h1>
  <% transport_items.each do |transport_item| %>
    <%= transport_item.name %><br>
  <% end %>
<% end %>

Upvotes: 1

theIV
theIV

Reputation: 25774

Just like you use instance_variable_set, there is an instance_variable_get available.

Upvotes: 1

Related Questions