2013-05-15 118 views
0

我正在使用Rails 3.2。我有以下代碼:如何迭代實例變量中的實例變量?

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

控制器代碼是正確的,但視圖代碼是錯誤的。 @transport.pluralize.each不能從字面上調用。預期的結果是:

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

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

我該怎麼做?

+1

我得到你沒有得到你的預期結果,但你得到了什麼?一個錯誤?輸出錯誤順序?哪一個給'@ transport.pluralize'的呼叫失敗了?需要更多一點繼續下去。 – theIV

+0

不能從字面上調用'@ transport.pluralize'。我沒有測試過這個,但我相信這不是寫它的方法。 – Victor

+1

你是在說循環?如果是這樣,就像你做'instance_variable_set'一樣,有一個'instance_variable_get'。那是你在做什麼? – theIV

回答

1

您不必爲它創建一個實例變量,只需使用一個陣列(或哈希):

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>] 
# ] 

在你看來:

<% @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 %> 
+0

很好。謝謝! – Victor