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

时间:2016-03-14 19:00:14

标签: ruby-on-rails foreign-keys foreign-key-relationship

我的应用有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

生成的迁移不会为我的保险表设置任何外键。我希望有两个外键,例如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

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

2 个答案:

答案 0 :(得分:0)

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

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关联,但除非您在迁移文件中故意配置密钥,否则不会自动生成密钥。< / p>

答案 1 :(得分:0)

运行以下迁移:

rails g migration AddUserIDToInsurances user:references

rails g migration AddVehicleIDToInsurances vehicle:references

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