2016-01-04 35 views
3

我目前正在使用Rails 4.2.4。问题是,当我跑如何使用Rails生成迁移以添加引用?

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 

这是为什么?

回答

1

add_reference只是一个方便的助手来生成一个整数字段,遵循在关联中使用的命名约定。由于schema.rb映射数据库模式,因此您希望看到特定的数据类型而不是更高级别的抽象。

我不确定为什么你会期望t.references,但你的期望是错误的。这也在add_reference文档中有解释。

创建user_id整数

add_reference(:products, :user) 
+0

好了,怎么会如果我生成的模型,而不是有所不同? 'rails g model文章分类:参考文献' –

+0

'model'生成器生成模型和迁移,而'migration'只生成迁移。无论您使用哪个生成器,迁移将是相同的。 –

+0

我的意思是当你像上面的例子那样生成模型时,Rails创建't.reference'字段 –