我邀请您像这样建立关联:
如果是这样,您应该将关联定义为:
国家:
has_many :recipes
食谱:
belongs_to :country
而且我认为您的第二个关联也不正确。
当您belongs_to :country
在 Recipe 模型中定义时,这意味着您的 Recipe 表必须有一个名为 的列country_id
。它是 Country 模型的外键。
在第一个定义关联中,Country
模型将有一个名为 的列recipe_id
,因此,每个国家/地区只有一个配方,这不是您想要的,对吧?为什么它不起作用?因为一个国家只有一个记录,所以一个国家只能有一个食谱,通过recipe_id
.
对于第一个关联,您的关联是一对一的(一个国家有一个食谱),而您实际上希望您的关联是一对多的(一个国家有很多食谱)。所以这就是为什么第一个关联不起作用的原因(第二个也是)。
The main thing you need to remember here is, what model you put a belongs_to
association, that model will have a column called 'association name'_id
. The different between using has_one
and belongs_to
only is where you put foreign key and the meaning of association. Check here to clearer.