Rails - 迁移后没有预期的外键

Rails - no expected foreign keys after migration

我的应用有 3 个模型,定义如下:

class User < ActiveRecord::Base
  has_many :vehicles, dependent: :destroy
  has_one :insurance, through: :vehicle
end

class Vehicle < ActiveRecord::Base
  belongs_to :user
  has_one :insurance, dependent: :destroy
end

class Insurance < ActiveRecord::Base
  belongs_to :vehicle
end

生成的迁移不会为我的保险设置任何外键 table。我希望有两个外键,比如 user_idvehicle_id.

生成的 schema.rb 文件如下所示:

ActiveRecord::Schema.define(version: 20160314141604) do

  create_table "insurances", force: :cascade do |t|
    t.string   "name"
    t.date     "issue_date"
    t.date     "expiry_date"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

  create_table "vehicles", force: :cascade do |t|
    t.text     "name"
    t.date     "matriculation_date"
    t.integer  "user_id"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
  end

  add_index "vehicles", ["user_id"], name: "index_vehicles_on_user_id"

end

为什么保险 table 没有外键?谢谢

您必须在迁移中专门设置关联键。如果您创建新的迁移并添加:

add_column :vehicles, :user_id, :integer
add_column :insurances, :user_id, :integer

add_index :vehicles, :user_id
add_index :insurances, :user_id
# or whatever columns and indexes you need...

Rails 为您提供了 has_one has_manybelongs_to 方法来方便地将模型与 ActiveRecord 相关联,但密钥不会自动生成,除非您有意配置它们在迁移文件中。

运行 以下迁移:

rails g migration AddUserIDToInsurances user:references

rails g migration AddVehicleIDToInsurances vehicle:references

然后运行rake db:migrate。这应该将您提到的两个外键添加到您的保险 table.