--000e0cd1b2eebd78b70482cf55d9
Content-Type: text/plain; charset=ISO-8859-1

On Sat, Mar 27, 2010 at 3:01 PM, Nicolas 2b <ndebonfils / gmail.com> wrote:

> Hi,
>
> My problem use RoR object but is ruby oriented so I post here.
> 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
> --
> Posted via http://www.ruby-forum.com/.
>
>
First, your syntax made it unclear what you wanted in the end, you said an
array, but then used hash rockets to indicate key/value pairs. I'm not sure
if I got it the way you are needing it.

-----

Probably, you should let the database do this for you. Since I don't know
how you are using it, I can't say for sure, but it sounds like you should be
using the SQL count function. The Rails ML will be better equipped to help
you.

products  roduct.all :select 'company_id , count(company_id)' , :group
'company_id'
products.each do |product|
  company_id  roduct.company_id
  count  roduct.attributes[ 'count(company_id)' ]
  puts "#{company_id}  {count}"
end

I'm not sure if there is a nicer way to pull this out than using the
attributes hash, but a quick test I ran had it working for me.

-----

If using sql isn't the best option for you, you can do something like this

product_counts  roducts.group_by do |product|
  product.company_id
end

product_counts.each do |company_id,products|
  product_counts[company_id]  roducts.size
end

p product_counts




On Sat, Mar 27, 2010 at 3:04 PM, Nicolas 2b <ndebonfils / gmail.com> wrote:

> Sorry for the errors in the title, if someone could correct them :S
> --
> Posted via http://www.ruby-forum.com/.
>
>
The forum is just an interface to a mailing list, you can't unsend email
(well... not really), so you can't correct them.

--000e0cd1b2eebd78b70482cf55d9--