0

기본적인 요리 책을 만들고 싶습니다. 요리법과 함께 성분 관계.레서피에 수량 추가 habtm 성분 관계

첫 번째 시도는 이와 같았습니다.

class Recipe < ActiveRecord::Base 
    # title, description 
    has_many :recipe_ingredients 
end 

class Ingredient < ActiveRecord::Base 
    # name, unit 
    has_many :recipe_ingredients 
    has_many :recipes, :through => :recipe_ingredients 
end 

class RecipeIngredient < ActiveRecord::Base 
    belongs_to :recipe 
    belongs_to :ingredient 
    attr_accessible :amount 
end 

그리고이 추한 느낌 손

RecipeIngredient.create(:recipe_id => 1, :ingredient_id => 2, :amount => 100) 

recipe.recipe_ingredients.amout 
recipe.recipe_ingredients.ingredient.unit 
recipe.recipe_ingredients.ingredient.name 

에 의해 관계를 만들었습니다. 그러나 나는 다른 해결책을 모른다.

답변

3

나에게 잘 보이지만 스키마/접근 방식입니다. 클래스 이름을 선택하면 "recipe.recipe_ingredients.ingredient"를 많이 입력하기 때문에 추한 느낌이들 수도 있습니다. 나에게 '재료'는 조리법에서 사용되는 음식/액체/무엇이든 상관 없으므로 조인 표는 '재료'라고해야합니다. 각 성분에는 양이 있고 "제품"또는 "품목"또는 유사한 것에 연결됩니다.

나는 이렇게 이름을 바꿀 것입니다 :보기 페이지에서 지금

Recipe 
    has_many :ingredients 
    has_many :items, :through => :ingredients 

Ingredient 
    #fields - recipe_id, item_id, quantity(string) 
    belongs_to :recipe 
    belongs_to :item 

Item 
    has_many :ingredients 
    has_many :recipes, :through => :ingredients 

당신이

<h2><%= recipe.name %></h2> 
<dl> 
    <% @recipe.ingredients.each do |ingredient| %> 
    <dt><%= ingredient.item.name %></dt> 
    <dd><%= ingredient.quantity %></dd> 
    <% end %> 
</dl> 
+1

야호 타이핑 recipes.recipes을 ... 나쁜입니다. 감사 – Henning

0

을 말할 수있는 당신이 has_many 없어진 것 같아요 : receipe 모델

클래스 Receipe <에 통해를 액티브 레코드 ::베이스

has_many : receipe_ingre dients

has_many : 재료 : receipe_ingredients

수준의 성분 < 액티브 :: 자료

has_many : receipe_ingredients

has_many : 조리법에, =>을 통해 = 통하여> : receipe_ingredients

end

클래스 ReceipeIngredient < 액티브 :: 자료

belongs_to : receipe

belongs_to : 성분