t.references :state, null: false (用法解释) - cwy007/tips-and-skills GitHub Wiki

添加 foreigen_key & index on foreigin_key

state_id 
"index_addresses_on_state_id" btree (state_id)
note: database is postgreql
class AddAddresses < ActiveRecord::Migration[5.1]
  def change
    create_table :states do |t|
      t.string     :code, size: 2, null: false
      t.string     :name,          null: false
    end

    create_table :addresses do |t|
      t.string     :street,        null: false
      t.string     :city,          null: false
      t.references :state,         null: false
      t.string     :zipcode,       null: false
    end

    create_table :customers_billing_addresses do |t|
      t.references :customer,      null: false
      t.references :address,       null: false
    end

    create_table :customers_shipping_addresses do |t|
      t.references :customer,      null: false
      t.references :address,       null: false
      t.boolean    :primary,       null: false, default: false
    end
  end
end

$ rails db 

shine_development=> \d addresses
                               Table "public.addresses"
  Column  |       Type        |                       Modifiers
----------+-------------------+--------------------------------------------------------
 id       | bigint            | not null default nextval('addresses_id_seq'::regclass)
 street   | character varying | not null
 city     | character varying | not null
 state_id | bigint            | not null
 zipcode  | character varying | not null
Indexes:
    "addresses_pkey" PRIMARY KEY, btree (id)
    "index_addresses_on_state_id" btree (state_id)

参考链接

[1] https://stackoverflow.com/questions/16309742/t-references-in-the-migration-vs-belongs-to-in-the-model

[2] book: Rails, Angular, Postgres, and Bootstrap 2nd.pdf