我有一张餐桌,一张配料桌和一张菜肴配料桌,可以加入菜肴和配料(见下文)。每次我添加一种成分到菜,我想增加或添加成分的数量到dish_ingredient表。我设法通过以下方式更新号码:
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 :(得分:0)
你试过吗
class DishIngredient < ActiveRecord::Base
belongs_to :dish
belongs_to :ingredient, :counter_cache => true
end
?这要求您在dish_ingredient表中具有ingredients_count
属性。 Rails会自动处理计数器的更新。
答案 1 :(得分:0)
出了什么问题:
some_dish.ingredients.count