如何从ActiveRecord CollectionProxy中获取值?

11

我在遍历一个集合属性以获取值时遇到了问题。

这是我的代理。

<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

当我循环代理时,我没有在新行上获取单个名称。我得到整个对象。我已经更新了我的问题并附上了输出。 - Jay
@joe你在rail console中运行@order.products.each do |a| a.name end的哪里了? - Surya
是的,它在我的Rails控制台中。@engineersmnky我尝试了所有这些,但我得到了相同的输出。 - Jay
@orders.products{|prod| puts prod.each(&:name)}是什么意思? - engineersmnky
3个回答

16

如果你想将所有名称放入一个数组中,你应该使用Enumerable#collect:

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

3
在你的Rails控制台中尝试以下操作:
@order.products.each do |p|
  puts p.name
end
# => test
# => aggg

puts会在执行后显示产品的名称(p.name),并添加一个换行符。


哈哈哈。完全没有意识到他是在控制台中运行这个程序。这是正确的答案@joe,你必须使用puts输出结果,#each只会返回原始对象。 - engineersmnky

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接