2015-09-04 69 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