Gus
Gus

Reputation: 90

Mondoid search one document with multiples in a has_many/belongs_to relationship

I have this releationship

class Cupboard
 include Mongoid::Document
 field :name, type: String
 has_many :ingredients 
end

class Recipe
 include Mongoid::Document
 field :name, type: String
 has_many :ingredients
end

class Ingredient
 include Mongoid::Document
 field :name, type: String
 field :description, type: String
 belongs_to :cupboard
 belongs_to :recipe
end 

I need to create a method in Cupboard model to find a recipe that contains the same ingredients as the cupboard, I don't find in the Mongoid docs a method to find it.

I need something like Recipe.find( #all cupboard.ingredients.ids )

thanks in advance

Upvotes: 0

Views: 66

Answers (1)

Pedro Nascimento
Pedro Nascimento

Reputation: 13916

def shared_recipes
  ingredients.map(&:recipe).uniq
end

Upvotes: 1

Related Questions