Victor
Victor

Reputation: 13368

How do I create instance variables from an array?

I'm using Rails 3.2. Here's my code:

transports = %w(car bike)

transports.each do |transport|
  @transport = transport.classify.all
end

That code is not working, but I want the results to be:

@cars = Car.all
@bikes = Bike.all

How do I do that?

Upvotes: 0

Views: 122

Answers (1)

toro2k
toro2k

Reputation: 19228

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

Update Given that the entries in the transports array are now singular the correct code to get the result you want is

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

Upvotes: 5

Related Questions