【问题标题】:Add association to existing model using a foreign key使用外键将关联添加到现有模型
【发布时间】:2014-05-21 20:29:32
【问题描述】:

假设你有这两个模型

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

将正确的列添加到汽车后,我的迁移会是什么样子?它应该是一个名为 driver_id 或 user_id 的列吗?

这是this question 的变体。

【问题讨论】:

  • 您最终可以使用belongs_to :driver, class_name: 'User' 并创建一个列driver_id
  • 列应该是driver_id。

标签: ruby-on-rails migration associations


【解决方案1】:

当您在关联中使用不同的foriegn_keys 时,您必须记住这些关联只会使用您提供的foreign_key

--

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

belongs_to :driver, foreign_key: "driver_id", class_name: "User"

迁移/表将如下所示:

add_column :cars, :driver_id, :integer

【讨论】:

  • 你不是说 add_column :cars, :driver_id, :integer 吗?
猜你喜欢
  • 2013-03-01
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2012-05-10
相关资源
最近更新 更多