如何从ActiveRecord CollectionProxy获取值?

时间:2014-10-31 18:58:44

标签: 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">, #<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">]>

我希望能够像这样遍历代理中的所有对象。

my_collection_proxy.each do |c| c.name end

但这似乎不起作用。如何获取代理中每个名称的值?

输出:

@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">]

我希望输出看起来像什么:

=> test
=> aggg

3 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:2)

在rails控制台中试试这个:

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

puts将显示产品名称(p.name)并在执行后添加换行符。

答案 2 :(得分:0)

使用了@record.property.map(&:to_s)