如何在视图中迭代实例变量中的实例变量?

时间:2013-05-15 02:10:55

标签: ruby-on-rails ruby

我正在使用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>

我该怎么做?

2 个答案:

答案 0 :(得分:1)

就像您使用instance_variable_set一样,有instance_variable_get可用。

答案 1 :(得分: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 %>