orgertot
orgertot

Reputation: 197

Ruby on Rails: Use existing Model if possible

I want to create a relationship from recipe to ingredients. Basically:

recipe has_many ingredients
ingredients belongs_to recipe

But if I add a ingredient to a recipe it should look if there is an existing ingredient with the same name and should use that one.

Is there a smooth solution?

Upvotes: 0

Views: 48

Answers (2)

nsave
nsave

Reputation: 984

Having all realations set up in a standart way (HABTM) you could add ingrediants by name like this:

# reciept.rb
def add_ingredient_by_name(ingredient_name)
  self.ingredients << Ingredient.find_or_create_by(name: ingredient_name)
end

Update: Also I'd add a uniqueness constraint for ingredient name for safety:

# ingredient.rb
validates_uniqueness_of :name

Upvotes: 0

Max Williams
Max Williams

Reputation: 32933

You need to expand your schema out: you need to differentiate between an ingredient like "all purpose flour", of which you want one in your database, and then "100 grams of all purpose flour" which might be used in a specific recipe.

I would do something like this:

Recipe
  has_many :recipe_ingredients
  #fields - name

RecipeIngredient
  belongs_to :ingredient
  belongs_to :recipe
  #fields - quantity

Ingredient
  has_many :recipe_ingredients
  #fields - name

Now, when you build a recipe, you're building a list of associated recipe_ingredients, each of which points to an ingredient (like the "all-purpose flour" ingredient) and has a quantity, eg "100 grams".

Note - i could have added "has_many :ingredients, :through => :recipe_ingredients" to Recipe, but i don't actually think this is a useful association: ingredients only make sense for the recipe when they have a quantity - i don't think you would ever want to say "recipe.ingredients" as this doesn't give you the quantity info.

Upvotes: 1

Related Questions