Ruby on Rails:尽可能使用现有模型
Ruby on Rails: Use existing Model if possible
我想建立从食谱到配料的关系。基本上:
recipe has_many ingredients
ingredients belongs_to recipe
但是,如果我在食谱中添加一种成分,它应该查看是否存在同名的现有成分,并应该使用该成分。
有没有顺利的解决方案?
您需要扩展您的模式:您需要区分一种成分,例如 "all purpose flour",您希望数据库中包含一种成分,然后区分可能会使用的“100 克通用面粉”在特定的食谱中。
我会这样做:
Recipe
has_many :recipe_ingredients
#fields - name
RecipeIngredient
belongs_to :ingredient
belongs_to :recipe
#fields - quantity
Ingredient
has_many :recipe_ingredients
#fields - name
现在,当您构建食谱时,您正在构建一个关联的 recipe_ingredients
列表,每个列表都指向一种成分(如 "all-purpose flour" 成分)并有一个数量,例如“100 克”。
注意 - 我本可以将 "has_many :ingredients, :through => :recipe_ingredients" 添加到食谱中,但我实际上并不认为这是一个有用的关联:成分只有在数量充足时才对食谱有意义 - 我不认为你会想说 "recipe.ingredients" 因为这不会给你数量信息。
以标准方式 (HABTM) 设置所有关系后,您可以像这样按名称添加配料:
# reciept.rb
def add_ingredient_by_name(ingredient_name)
self.ingredients << Ingredient.find_or_create_by(name: ingredient_name)
end
更新:
另外,为了安全起见,我会为成分名称添加唯一性约束:
# ingredient.rb
validates_uniqueness_of :name
我想建立从食谱到配料的关系。基本上:
recipe has_many ingredients
ingredients belongs_to recipe
但是,如果我在食谱中添加一种成分,它应该查看是否存在同名的现有成分,并应该使用该成分。
有没有顺利的解决方案?
您需要扩展您的模式:您需要区分一种成分,例如 "all purpose flour",您希望数据库中包含一种成分,然后区分可能会使用的“100 克通用面粉”在特定的食谱中。
我会这样做:
Recipe
has_many :recipe_ingredients
#fields - name
RecipeIngredient
belongs_to :ingredient
belongs_to :recipe
#fields - quantity
Ingredient
has_many :recipe_ingredients
#fields - name
现在,当您构建食谱时,您正在构建一个关联的 recipe_ingredients
列表,每个列表都指向一种成分(如 "all-purpose flour" 成分)并有一个数量,例如“100 克”。
注意 - 我本可以将 "has_many :ingredients, :through => :recipe_ingredients" 添加到食谱中,但我实际上并不认为这是一个有用的关联:成分只有在数量充足时才对食谱有意义 - 我不认为你会想说 "recipe.ingredients" 因为这不会给你数量信息。
以标准方式 (HABTM) 设置所有关系后,您可以像这样按名称添加配料:
# reciept.rb
def add_ingredient_by_name(ingredient_name)
self.ingredients << Ingredient.find_or_create_by(name: ingredient_name)
end
更新: 另外,为了安全起见,我会为成分名称添加唯一性约束:
# ingredient.rb
validates_uniqueness_of :name