假设我有产品<类别和产品 belongs_to
类别
是否t.reference :category
取代了对belongs_to
或has_one
关联的需求?
它会自动生成表格中的category_id
吗?
答案 0 :(得分:1)
references
只是belongs_to
的别名。这是同样的方法。您可以在source code中看到。
alias :belongs_to :references
它会自动在表中生成父外键。它与模型中的关联声明无关。你仍然必须专门写这些。 references
和belongs_to
都是添加外键列的快捷方式。
请注意,此处的belongs_to
位于迁移的上下文中,而不是模型关联belongs_to
。
答案 1 :(得分:0)
对于ActiveRecord,一个只是另一个的别名。
references
是原始方法(link to doc),belongs_to
是references
(link to doc)的别名。
请注意,还有另一种ActiveRecord方法#references
可以执行不同的操作(link to doc)