i'm having trouble looping through a collection property to get out values.
This is my proxy
<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">]>
I want to be able to loop through all of the objects in the proxy like this.
my_collection_proxy.each do |c| c.name end
But that doesn't seem to be working. How do I get the value of each name in the proxy?
Output:
@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">]
What I want my output to look like:
=> test
=> aggg
Try this in your rails console:
@order.products.each do |p|
puts p.name
end
# => test
# => aggg
puts
will display product's name(p.name
) and adds a newline after executing.
If you're trying to pull all the names into an array, you should use Enumerable#collect:
names = @order.products.collect(&:name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With