Topic: help to get value from an array of objects

Hi,

I got an array with lot of objects (type 'Product') like this (only 4 here) :

[#<Product id: 295147, company_id: 1>, #<Product id: 303667, company_id: 2>, #<Product id: 279561, company_id: 9>, #<Product id: 289477, company_id: 4>]

What I want to do is iterate on the array and for each company_id, know how much products have the same company_id.
I get the company_id like this : products.collect(&:company_id).uniq

but after I don't know how to get an array like this : [1 => 22, 2 =>15, 3 => 9]

Thanks for your help

---
Nicolas

Re: help to get value from an array of objects

The first thing I'd suggest is not to use .uniq.  That will take a really long time to execute if your table has many rows.  You should use the SELECT DISTINCT method like this.

Product.find( :all, :select => 'DISTINCT company_id' )

Or, in your case, like this.

@products = Product.count(:distinct => true, :select => :company_id)
=> "SELECT count(DISTINCT company_id) AS count_company_id FROM products"

This is untested, and probably won't work as is.  You'd call it from the view like this...

<% @products.each do |product| %>
    <%= product.count_company_id %>
<% end %>

Good luck

Last edited by zreed20 (2010-03-29 19:09:11)

Re: help to get value from an array of objects

nicolas2b wrote:

but after I don't know how to get an array like this : [1 => 22, 2 =>15, 3 => 9]

I think that the best way to do it, is making a proper query:

products = Product.count(:all, :group => "company_id")
=> {1 => 198198, 2 => 1928298, 6 => 878780}

As a result you will have an hash instead of an array.

Hope this helps

Re: help to get value from an array of objects

you should do it manually using iterating code / looping.

form an array of hash.