0

デモアプリのRails3のモデルを使用して、多対多の関係を実装しようとしています。
リレーションに関するデータをもう少し保持するモデルを追加しようとするまで、すべて正常に機能しました。
レシピ、材料、Ingredient_Recipeモデルがあります

ファイル:ingredient_recipe.rb

class IngredientRecipe < ActiveRecord::Base
  attr_accessible :created_at, :ingredient_id, :order, :recipe_id
  belongs_to :recipes
  belongs_to :ingredients
end

ファイル:ingredient.rb

class Ingredient < ActiveRecord::Base
 has_many :ingredientRecipe
 has_many :recipes, :through => :ingredientRecipe
 ...

File:recipes.rb

 class Recipe < ActiveRecord::Base
  has_many :ingredientRecipe
  has_many :ingredients, :through => :ingredientRecipe
  ...

UIで

 <td >
  <% @recipe.ingredients.each do |ingredient| %>
   ingredient.name
  <% end %>
 </td >

テーブル

 ingredient_id, recipe_id, order, created_at, updated_at

さて、これはあまりうまくいきません...

まあ、そして多対多を実装するための良いリソースは非常に高く評価されます

4

1 に答える 1

1

モデルコードにいくつかのエラーがあります。それらが何をするかを正確に言うのは難しいです。

レシピモデルは次のようになります。

has_many :ingredient_recipes
has_many :ingredients, :through => :ingredient_recipes

材料モデルは次のようになります

has_many :ingredient_recipes
has_many :recipes, :through => :ingredient_recipes 

関連付けには下線を付けて小文字にする必要があり、has_many関係は複数形にする必要があります。

含まれているとIngredient_Recipeおっしゃいましたが、内容は良いですが、名前を付ける必要があり、クラス名はそれが私の誤解であるかどうかわからないingredient_recipe.rbはずです。IngredientRecipe

あなたが経験している最初のエラーはrecipe_ingredient、意味のある未定義のメソッドです。アソシエーション名はですingredient_recipes。throughパラメータはアソシエーションの正確な名前を取ります。

2番目の問題は言うのが難しいですが、私は最初に上記の変更を行い、それが状況を改善するかどうかを確認します。

3番目の項目、私はノーと言うでしょう。railscastの指示に従ってください。

問題のrailscastは良いリソースです、私は以前にその特定のものを使用しました。

編集、belongs_toも正しくないことに気づきました。

IncredientRecipeクラス内

belongs_to :recipe
belongs_to :ingredient

belongs_to関連付けは特異である必要があります。

于 2012-06-09T13:56:09.703 に答える