如何在rails 5中为现有模型添加外键

问题描述 投票:0回答:1

为了简化,请假设我的架构是here(或者看下一句 - 我的实际表非常相似,因为我有两个表,我试图通过另一个外键中的主键加入)

因此,对于该示例,我们具有:具有PersonID作为主键的Persons表,以及具有PersonID作为外键的Orders表。

假设我的应用程序中已经存在没有关联的表格,我相信我会做以下事情:

  1. has_many :orders放在Persons模型中,将belongs_to :person放在Order模型中
  2. 生成新的迁移,例如rails g migration migrationName

我不知道下一步该做什么。我认为这是将它放在迁移文件中(并运行rake db:migrate)?

add_foreign_key :orders, :person

在我的实际表中,外键列有一个有趣的名称(与它加入的表无关) - 我认为我需要做的可能会改变但是我不确定?

最后一点,我知道有人会建议我读this。事情是我花了几个小时阅读它和其他来源,我在我试图定义的关联中有几个其他复杂因素(关联在两个表上是可选的),我也不知道如何快速判断它是否实际工作(目前我尝试在rails控制台中使用一些Arel代码来查看连接是否返回任何结果 - 我不知道存在任何更简单的方法)

ruby-on-rails ruby-on-rails-5 rake-task
1个回答
0
投票

我通过随机谷歌搜索遇到了这个问题,因为我正在寻找类似的东西。创建您的迁移并确保它看起来像这样:

class AddPersonToOrders < ActiveRecord::Migration[5.1]
  def change
    # No need for this line because you said:
    # "an Orders table, with PersonID as a foreign key"
    # add_reference   :orders, :person

    # This is what I think you are missing:
    add_foreign_key :orders, :persons, column: :person_id
    # If this doesn’t work, try to change the `person_id`
    # column name to that funny column name you say you have.
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.