How to get values ​​from ActiveRecord CollectionProxy?

I am having a problem looping through a collection property to get the 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 objects in the proxy like this.

my_collection_proxy.each do |c| c.name end

      

But that doesn't seem to work. 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">]

      

I want my output to look like this:

=> test
=> aggg

      

+3


source to share


2 answers


If you are trying to output all names to an array, you should use Enumerable # collect:



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

      

+8


source


Try this in your rails console:

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

      



puts

will display the product name ( p.name

) and add a new line after execution.

+2


source







All Articles