Jay*_*Jay 7 ruby ruby-on-rails
我在循环收集属性以获取值时遇到问题.
这是我的代理人
<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">]>
Run Code Online (Sandbox Code Playgroud)
我希望能够像这样遍历代理中的所有对象.
my_collection_proxy.each do |c| c.name end
Run Code Online (Sandbox Code Playgroud)
但这似乎并没有奏效.如何获取代理中每个名称的值?
输出:
@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">]
Run Code Online (Sandbox Code Playgroud)
我希望我的输出看起来像:
=> test
=> aggg
Run Code Online (Sandbox Code Playgroud)
小智 10
如果您尝试将所有名称拉入数组,则应使用Enumerable#collect:
names = @order.products.collect(&:name)
Run Code Online (Sandbox Code Playgroud)
Try this in your rails console:
@order.products.each do |p|
puts p.name
end
# => test
# => aggg
Run Code Online (Sandbox Code Playgroud)
puts will display product's name(p.name) and adds a newline after executing.