Ruby on rails 如何从ActiveRecord CollectionProxy获取值?

Ruby on rails 如何从ActiveRecord CollectionProxy获取值?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我在循环集合属性以获取值时遇到问题 这是我的代理人 <ActiveRecord::Associations::CollectionProxy [#<Product id: 12, name: "test", cost_in_cents: 4400, created_at: "2014-10-31 17:18:58", updated_at: "2014-10-31 17:18:58", subscription: nil, product_type: "One Time">,

我在循环集合属性以获取值时遇到问题

这是我的代理人

<ActiveRecord::Associations::CollectionProxy [#<Product id: 12, name: "test", cost_in_cents: 4400, created_at: "2014-10-31 17:18:58", updated_at: "2014-10-31 17:18:58", subscription: nil, product_type: "One Time">, #<Product id: 14, name: "aggg", cost_in_cents: 1400, created_at: "2014-10-31 17:28:19", updated_at: "2014-10-31 17:28:19", subscription: nil, product_type: "One Time">]>
但这似乎不起作用。如何获取代理中每个名称的值

输出:

@order.products.each do |a| a.name end
=> [#<Product id: 12, store_front_id: 8, name: "test", cost_in_cents: 4400, created_at: "2014-10-31 17:18:58", updated_at: "2014-10-31 17:18:58", subscription: nil, product_type: "One Time">, #<Product id: 14, store_front_id: 8, name: "aggg", cost_in_cents: 1400, created_at: "2014-10-31 17:28:19", updated_at: "2014-10-31 17:28:19", subscription: nil, product_type: "One Time">]

在rails控制台中尝试以下操作:

@order.products.each do |p|
  puts p.name
end
# => test
# => aggg

put
将显示产品名称(
p.name
),并在执行后添加新行。

如果试图将所有名称拉入数组,则应使用Enumerable#collect:

name=@order.products.collect(&:name)

使用了
@record.property.map(&:to_s)
因此,当我在代理中循环时,我不会在新行中返回单个名称。我得到了整个物体。我用一个输出更新了我的问题。@joe你在哪里运行rail控制台中的
@order.products.each do | a | a.name end
?是的,它在我的rails控制台中@工程师:我尝试了所有这些,得到了相同的结果。那么
@orders.products{| prod | put prod.each(&:name)}
?哈哈哈。我完全不知道他是在控制台上运行的。这是正确的答案@joe您必须使用put
#输出结果,每个
仅返回原始对象。
=> test
=> aggg
@order.products.each do |p|
  puts p.name
end
# => test
# => aggg