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”
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")