许多一对多
您通常需要使用一个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
+1此解决方案 – MrYoshiji