2014-07-21 41 views
1

我有一个菜食谱它有许多杂货在这种情况下 - 什么更好有很多或有很多通过?

class Dish < ActiveRecord::Base 
    has_many :groceries 

我正在cosidering - 我应该让简单的像上面的例子,但有,比方说, 100菜肴,每一个有西红柿,胡萝卜,cucambers - 所以杂货表将大 与同样的食品杂货或我应该使用有很多通过和做杂货表 ,然后加入连接菜肴和杂货,所以杂货店表很小,说 只有西红柿胡萝卜和cucambers,但连接表将很大,以连接所有的菜肴和杂货。

如果没关系我倾向于第一种 - 它的很多更简单的程序......

回答

6

的优点“有许多通过”是双重的...

首先,由于杂货项目是表驱动你最大限度地减少拼写错误和食谱中的变幻莫测(例如一个配方有“西红柿”,另一个配方有“西红柿”)

第二,如果你让它有很多通过你可以使它成为一个双向关系,所以你可以做...

carrots = Grocery.find_by(name: "carrots") 

carrots.recipes # show all the recipes using carrots 
+0

+1此解决方案 – MrYoshiji

0

许多一对多

您通常需要使用一个many-to-many Rails中加入这样的事情,因为除非你每次dish实际上创建groceries是,它将是非常低效的&“WET”

在我看来,关联这两种数据类型的方式是使用连接模型 - 有两种方法可以做到这一点:

根据您的系统需要如何工作,has_many :through可能比has_and_belongs_to_many稍微更多的工作;它的好处是,你可以附加很多不同的数据互传的加入记录,而has_and_belongs_to_many只有关联两个类型的记录的


has_and_belongs_to_many

如果您没有添加任何具体细节连接表,你会希望使用has_and_belongs_to_many

#app/models/dish.rb 
Class Dish < ActiveRecord::Base 
    has_and_belongs_to_many :groceries 
end 

#app/models/grocery.rb 
Class Grocery < ActiveRecord::Base 
    has_and_belongs_to_many :dishes 
end 

这将允许您创建下表:

#dishes_groceries 
dish_id | grocery_id 

因此允许你调用如下

@dish = Dish.find params[:id] 
@dish.grocies.each do |grocery| 
    grocery.name #-> "Carrot" 
end 

-

的has_many:通过

如果你想使用has_many :through,你就必须做出单独的模型,这将允许您包含其他属性(因为其附带的表将具有primary_key):

#app/models/dish.rb 
Class Dish < ActiveRecord::Base 
    has_many :dish_groceries 
    has_many :groceries, through: :dish_groceries 
end 

#app/models/dish_grocery.rb 
Class DishGrocery < ActiveRecord::Base 
    belongs_to :dish 
    belongs_to :grocery 
end 

#app/models/grocery.rb 
Class Grocery < ActiveRecord::Base 
    has_many :dish_groceries 
    has_many :dishes, through: :dish_groceries 
end 
相关问题