我正在使用 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>
我该怎么做呢?