【问题标题】:Rails 4.2: Turn a reference field into foreign keyRails 4.2:将引用字段转换为外键
【发布时间】:2017-12-05 17:38:38
【问题描述】:

我正在维护一个使用 Rails 4.2 的旧系统,由于未知原因,这些引用是以这种方式创建的:

  t.references :credit_card, null: false
  t.references :car, null: false
  t.references :profile, null: false

这允许我为此模型创建具有无效信用卡 ID 的寄存器,例如。 外键未经过验证。

生成索引迁移并没有将它们变成 fk 并且根本没有验证它们:

class AddIndexToRentals < ActiveRecord::Migration
  def change
    add_index :rentals, :credit_card_id
    add_index :rentals, :car_id
    add_index :rentals, :profile_id
  end
end

如何使这些字段成为外键并只接受现有的 ID?

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-4 indexing foreign-keys


    【解决方案1】:

    您可以向迁移添加外键以验证引用记录的存在、生成迁移并执行以下操作。

    class AddForeignKeyToRentals < ActiveRecord::Migration
      def change
        add_foreign_key :rentals, :credit_cards
        add_foreign_key :rentals, :cars
        add_foreign_key :rentals, :profiles
      end
    end
    

    需要注意的一点是,如果您有外键列中不存在的记录,您将无法运行此迁移。您还可以在模型中添加额外的存在验证。

    validates :credit_card, :car, :profile, presence: true
    

    希望这会有所帮助! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多