我正在尝试制作基于Rails的应用程序(我只是在学习RoR),我偶然发现了这个问题。
有两种型号:配方和物品(食品)。配方可以为零(我们可以在添加项目之前创建配方)或许多项目。但是特定食品不应该与任何配方绑定。这就是为什么'has_many'和'belongs_to'对我不起作用,因为后者不满足这个要求。
如果我在没有任何框架的情况下这样做,我可能会在Recipe表中放入一个'items'列,其中包含一个项目索引列表。但我有一种预感,因为在Rails中存在模型关联,所以这不是在RoR中执行此操作的合适方法。拜托,有人可以告诉我如何解决这个问题吗?
我通常不使用has_and_belongs_to_many,但在你的情况下似乎它可能适合。你可以像这样使用它:
class Recipe
has_and_belongs_to_many :items
end
class Item
has_and_belongs_to_many :recipes
end
您也可以使用has_many:through,但您必须创建第三个表以将Recipe和Item表连接在一起。
class Recipe
has_many :item_recipes
has_many :items, through: :item_recipes
end
class ItemRecipes
belongs_to :recipe
belongs_to :item
end
class Item
has_many :item_recipes
has_many :recipes, through: :item_recipes
end
您可以在这里找到更多信息:Rails Associations