Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get values from a ActiveRecord CollectionProxy?

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
like image 295
Jay Avatar asked Oct 31 '14 18:10

Jay


2 Answers

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.

like image 144
Surya Avatar answered Nov 17 '22 09:11

Surya


If you're trying to pull all the names into an array, you should use Enumerable#collect:

names = @order.products.collect(&:name)
like image 26
showaltb Avatar answered Nov 17 '22 09:11

showaltb