Ruby on rails 使用外键向现有模型添加关联

Ruby on rails 使用外键向现有模型添加关联,ruby-on-rails,migration,associations,Ruby On Rails,Migration,Associations,假设你有这两种型号 rails generate model User rails generate model Car 现在,我想添加一个关联,以便模型获得该表单 class User < ActiveRecord::Base has_many :cars en class Car < ActiveRecord::Base belongs_to :driver, foreign_key: "driver_id", class_name: "User" end class

假设你有这两种型号

rails generate model User
rails generate model Car
现在,我想添加一个关联,以便模型获得该表单

class User < ActiveRecord::Base
  has_many :cars
en
class Car < ActiveRecord::Base
  belongs_to :driver, foreign_key: "driver_id", class_name: "User"
end
class用户
将适当的列添加到car中,我的迁移会是什么样子?它应该是名为driver\u id或user\u id的列吗

这是上的一个变体。

当您在关联中使用不同时,您必须记住这些关联将仅使用您提供的
外键

--

这意味着如果您希望使用此关联:

belongs_to :driver, foreign_key: "driver_id", class_name: "User"
迁移/表如下所示:

add_column :cars, :driver_id, :integer

您最终可以使用
属于:driver,class\u name:'User'
,只需创建一列
driver\u id
它应该是
driver\u id
作为列。您的意思是添加列:cars,:driver\u id,:integer吗?