0

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?

5
  • 1
    I get that you are not getting your expected result, but what are you getting? An error? Output is in the wrong order? Which call to @transport.pluralize is failing? Need a little more to go on here. Commented May 15, 2013 at 2:13
  • The @transport.pluralize cannot be called literally. I haven't tested this, but I'm sure that is not the way to write it. Commented May 15, 2013 at 2:23
  • 1
    Are you talking about in the loop? If so, just like you do instance_variable_set, there is an instance_variable_get. Is that what you're getting at? Commented May 15, 2013 at 2:26
  • Great great. That's what I wanted. Thanks for the tip. You can put that as an answer, then I will tick it, so that you get points. Thanks again. Commented May 15, 2013 at 2:28
  • glad that's what you were looking for. Submitted as an answer. Cheers. Commented May 15, 2013 at 2:30

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.