开发者

Is there a simple way to add data to a relation table in Rails?

I have a dish table, a ingredient table and a dish_ ingredient table to join dish and ingredient (see below). Every time I add a ingredient to dish, I want to increase or add the number of ingredients to the dish_ingredient table. I have manage to update the number by doing:

dish.dish_ingredients[counter].number_of_ingredients = new number

but by doing it this way I need to manage a counter. Is there a simple way to do this in 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_ingre开发者_StackOverflow社区dients
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.


Have you tried

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

? This requires you to have an ingredients_count attribute in the dish_ingredient table. Rails will automatically handle updates to the counter.


What's wrong with :

some_dish.ingredients.count
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜