2011-07-11 5 views
0

私は、皿と成分(以下を参照)に参加するために皿のテーブル、原料のテーブルと皿のテーブルを持っています。私が料理に原料を加えるたびに、dish_ingredientテーブルに食材の数を増やしたり追加したりしたいと思います。Railsのリレーションテーブルにデータを追加する簡単な方法はありますか?

dish.dish_ingredients[counter].number_of_ingredients = new number 

このようにすれば、カウンタを管理する必要があります。 Railsでこれを行う簡単な方法はありますか?

class Dish < ActiveRecord::Base 
    has_many :dish_ingredients 
    has_many :ingredients, :through => :dish_ingredients 
end 

class Ingredient < ActiveRecord::Base 
    has_many :dish_ingredients 
    has_many :dishes, :through => :dish_ingredients 
end 

class DishIngredient < ActiveRecord::Base 
    belongs_to :dish 
    belongs_to :ingredient 
end 

# in the database table dish_ingredient contains a field 'number_of_ingredients' 
# that I want to update when ingredients are modified or added to dish. 

答えて

0

あなたは

class DishIngredient < ActiveRecord::Base 
    belongs_to :dish 
    belongs_to :ingredient, :counter_cache => true 
end 

を試してみましたか?これには、dish_ingredientテーブルにingredients_count属性が必要です。 Railsはカウンタの更新を自動的に処理します。

+0

これはあなたの問題を解決しましたか? – emrass

+0

いいえ、私が探しているものではありません。値を増減するだけでなく、関連付けテーブルに値を設定できるようにする必要があります。 – Fossmo

0

の何が問題なのです:

some_dish.ingredients.count 
関連する問題