2015-09-04 65 views
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行被创建(而不是更新)。所有新排中的成分都是零。我明显忽略了关联的定义。我做错了什么?

谢谢!

回答

0

我认为这将让你更接近你在找什么:这当然

class User < ActiveRecord::Base 
    has_many :recipes 
end 

class Ingredient < ActiveRecord::Base 
    has_many :recipe_ingredients 
    has_many :recipes, through: :recipe_ingredients 
end 

class Unit < ActiveRecord::Base 
    has_many :recipe_ingredients 
    has_many :ingredients, through: :recipe_ingredients 
end 

class Recipe < ActiveRecord::Base 
    belongs_to :user 
    has_many :recipe_ingredients 
    has_many :ingredients, through: :recipe_ingredients 
    accepts_nested_attributes_for :recipe_ingredients 
end 

class RecipeIngredient < ActiveRecord::Base 
    belongs_to :recipe 
    belongs_to :ingredient 
    belongs_to :unit 
end 

假定您已经设置了所有的模型与正确的字段/索引。 Recipe需要有user_id字段,RecipeIngredient需要有recipe_id, ingredient_id, unit_id字段。

我从来没有建立一个4路连接表(只是通常的3路,即用户,办公室和约会模型,其约会属于用户和办公室)。但这应该起作用,至少稍加修改即可。如果您有任何问题,请告诉我。

+0

你能详细说明为什么配料需要在食谱中引用吗?我的想法是食谱有一个RecipeIngredient和RecipeIngredient有一个成分。我不明白为什么食谱模型有必要了解其家属之间的关系。你能帮我理解吗? – mjenkins

+0

当然,我想你可以在'Recipe'下找到所有'Ingredients'的列表,这样你就可以做'@ recipe.ingredients'。它需要引用'RecipeIngredient',因为这是连接三个模型的'连接表'。 – DerProgrammer

+0

你可能想要改变嵌套,使它更简单,并有如下形式:'User' has_many'Recipes','Recipes' has_many'Ingredients','Ingredients' has_one'Unit'。 – DerProgrammer