【问题标题】:Using rails migration generator to add foreign key使用 Rails 迁移生成器添加外键
【发布时间】:2016-01-09 10:59:22
【问题描述】:
rails 4.2.4
ruby 2.2.1

要自动生成国家/地区迁移,我会这样做:

rails g migration CreateCountry abbreviation:string status:string search_operations_id:integer

我想在生成的迁移文件中添加外键:

add_foreign_key :countries, :search_operations, on_delete: :cascade

如何使用 rails g 迁移命令来做到这一点?

【问题讨论】:

  • 老实说,我不知道这是否可以通过生成器完成,但我知道 Rails 的生成器无法完成迁移中您可能想要的所有操作。为什么不在生成迁移后手动添加add_foreign_key 语句?
  • 是的,我知道我可以手动添加它。这就是我现在所做的。我正在寻找一种自动捷径来完成它,它比生成一个空的迁移文件然后将语句添加到它更简单
  • 您可以使用自动迁移来完成,但您需要手动添加on_delete: :cascade 选项。 Rails 生成器不支持从命令行添加所有选项。

标签: ruby-on-rails activerecord ruby-on-rails-4.2


【解决方案1】:

与其在迁移中手动添加 search_operations_id,不如说:

rails g migration CreateCountry ... search_operations:references

当 Rails 生成迁移时,您应该会看到如下内容:

class CreateCountry < ActiveRecord::Migration
  def change
    ...
    add_reference :countries, :search_operations, index: true
    add_foreign_key :countries, :search_operations
  end
end        

【讨论】:

  • on_delete :cascade 将不存在,这实际上会产生一个 t.references :search_operations, index: true, foreign_key: true 迁移的目标是删除属于 search_operation 的国家/地区search_operation 已删除
  • 是的,不幸的是...我认为您无法在不手动添加的情况下获得 on_delete :cascade...
猜你喜欢
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 2017-01-16
  • 2013-02-16
  • 1970-01-01
  • 2019-01-29
  • 2016-02-11
相关资源
最近更新 更多