0
我想捕获轨道模型中的数据层次结构,并遇到一些麻烦。这里是一个分析图:https://www.lucidchart.com/invitations/accept/5744614c-2054-4f79-a842-8118e985f840在轨中建模多个关联
我的模型是用户,食谱,食谱成分,成分和单位。
- 用户自己的食谱。一个用户可以有零食到多食谱。
- 食谱有零至多个配方成分。食谱成分是 食谱的依赖者。
- RecipeIngredient正好指向一个食谱和一个配料 和一个单位。
- 单位和成分都不是RecipeIngredient的依赖。
- 配料可用于多种配方成分。
- 单位可以用于多个RecipeIngredients。
这里是我的模型定义:
class User < ActiveRecord::Base
end
class Ingredient < ActiveRecord::Base
end
class Unit < ActiveRecord::Base
end
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
accepts_nested_attributes_for :recipe_ingredients
end
class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
我在我的编辑形式使用这样的:
<%= f.fields_for :recipe_ingredients do |recipe_ingredient| %>
<%= recipe_ingredient.collection_select(:ingredient_id, Ingredient.all, :id, :name) %>
<%= recipe_ingredient.number_field :quantity, :step => 'any' %>
<%= recipe_ingredient.collection_select(:unit, Unit.all, :name, :name) %>
<%= recipe_ingredient.text_field :comment %>
当我提交表单,配方正确更新,但新RecipeIngredient行被创建(而不是更新)。所有新排中的成分都是零。我明显忽略了关联的定义。我做错了什么?
谢谢!
你能详细说明为什么配料需要在食谱中引用吗?我的想法是食谱有一个RecipeIngredient和RecipeIngredient有一个成分。我不明白为什么食谱模型有必要了解其家属之间的关系。你能帮我理解吗? – mjenkins
当然,我想你可以在'Recipe'下找到所有'Ingredients'的列表,这样你就可以做'@ recipe.ingredients'。它需要引用'RecipeIngredient',因为这是连接三个模型的'连接表'。 – DerProgrammer
你可能想要改变嵌套,使它更简单,并有如下形式:'User' has_many'Recipes','Recipes' has_many'Ingredients','Ingredients' has_one'Unit'。 – DerProgrammer