我目前正在使用 Rails 4.2.4。事情是当我跑rails g migration AddCategoryRefToArticles category:references
命令,
它生成了以下迁移
def change
add_reference :articles, :category, index: true, foreign_key: true
end
由于某种原因导致
category_id
作为整数字段而不是预期的 t.references。create_table "articles", force: :cascade do |t|
t.string "title"
t.integer "category_id"
end
add_index "articles", ["category_id"], name: "index_articles_on_category_id", using: :btree
为什么会这样?
最佳答案
add_reference
只是一个方便的助手,用于生成遵循关联中使用的命名约定的整数字段。由于 schema.rb
映射数据库模式,因此您应该看到特定的数据类型而不是更高级别的抽象。
我不确定为什么您会期望 t.references
,但您的期望是错误的。这也在 add_reference
文档中进行了解释。