PEF
PEF

Reputation: 973

How do I find instances with a given number of related objects in Ruby?

I have an array of hashes called messages:

messages = [{ "id" => "1", "name" => "John", "content" => "xxxxx", "product" => "1" },
 { "id" => "2", "name" => "John", "content" => "yyyyy", "product" => "3" },
 { "id" => "3", "name" => "Paul", "content" => "zzzzzz", "product" => "3" },
 { "id" => "4", "name" => "George", "content" => "xxyyzz", "product" => "2" }]

The messages belong to a product:

class Message < ActiveRecord::Base   
  belongs_to :product
end

How can I find the products with a given number of messages? e.g. find products with messages > 1 would give product "3"

Upvotes: 0

Views: 56

Answers (2)

socha23
socha23

Reputation: 10239

Group messages by product, and select products with more than one message.

messages.group_by(|m| m['product']).select{|p, mList| mList.length() > 1}.keys()

If you want to retrieve Product instances from DB, use ActiveRecord methods:

Product.joins(:messages).group("id").having("count(*) > 1")

Upvotes: 2

Chowlett
Chowlett

Reputation: 46667

My initial thought is the following:

prod_ids = messages.map{|m| m["product"]}.uniq
prod_ids.select {|prod| prod_ids.count(prod) > 1}

That is; extract an array of the product numbers, remove duplicates. Then choose from that array those numbers which appear in the array more than once.

Upvotes: 0

Related Questions