0

我正在使用 Rails 3.2。这是我的代码:

transports = %w(car bike)

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

该代码不起作用,但我希望结果是:

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

我怎么做?

4

1 回答 1

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

更新鉴于transports数组中的条目现在是单数的,因此获得所需结果的正确代码是

transports.each do |transport|
  instance_variable_set("@#{transport.pluralize}", 
                        transport.classify.constantize.all)
end
于 2013-05-14T14:26:15.870 回答