On Sat, Mar 27, 2010 at 3:01 PM, Nicolas 2b [email protected]
wrote:
What I want to do is iterate on the array and for each company_id, know
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 = Product.all :select => ‘company_id , count(company_id)’ ,
:group
=> ‘company_id’
products.each do |product|
company_id = product.company_id
count = product.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 = products.group_by do |product|
product.company_id
end
product_counts.each do |company_id,products|
product_counts[company_id] = products.size
end
p product_counts
On Sat, Mar 27, 2010 at 3:04 PM, Nicolas 2b [email protected]
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.