我正在使用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>
我該怎麼做?
我得到你沒有得到你的預期結果,但你得到了什麼?一個錯誤?輸出錯誤順序?哪一個給'@ transport.pluralize'的呼叫失敗了?需要更多一點繼續下去。 – theIV
不能從字面上調用'@ transport.pluralize'。我沒有測試過這個,但我相信這不是寫它的方法。 – Victor
你是在說循環?如果是這樣,就像你做'instance_variable_set'一樣,有一個'instance_variable_get'。那是你在做什麼? – theIV