简体   繁体   中英

How to use Rails generate migration for adding a reference?

I'm currently using Rails 4.2.4. The thing is when I ran

rails g migration AddCategoryRefToArticles category:references command,

It generated the following migration

def change
  add_reference :articles, :category, index: true, foreign_key: true
end

that for some reason resulted category_id as integer field and not expected 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

Why is this so?

add_reference is just a convenient helper to generate an integer field that follow the naming conventions to be used in an association. Since the schema.rb maps the database schema, it is expected that you see the specific data type rather than an higher level abstraction.

I'm not sure why you would expect a t.references , but your expectation is wrong. This is also explained in the add_reference documentation.

Create a user_id integer column

 add_reference(:products, :user) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM