t.reference :category 是否真的取代了 belongs_to 关联?

Does t.reference :category actually replaces the belongs_to association?

假设我有 Product < Category,还有一个 Product belongs_to Categoryt.reference :category 代替 belongs_tohas_one 协会的需要? 它会自动在 table 中生成 category_id 吗?

references 只是 belongs_to 的别名。这是相同的方法。你可以在source code中看到。

alias :belongs_to :references

它自动生成table中的父外键。它与模型中的关联声明无关。您仍然必须专门编写这些。 referencesbelongs_to 都是添加外键列的快捷方式。

请注意,这里的 belongs_to 是在迁移的上下文中,而不是模型关联 belongs_to

对于 ActiveRecord,一个只是另一个的别名。

references是原方法(link to doc), and belongs_to is an alias for references (link to doc).

注意 ActiveRecord 的另一个方法 #references 做不同的事情 (link to doc)