【问题标题】:ActiveRecord: how to throw exception when reference key not existActiveRecord:当引用键不存在时如何抛出异常
【发布时间】:2016-08-06 16:34:43
【问题描述】:

例如,我有两个模型:

class CheckInDetail < ApplicationRecord
  belongs_to :product
end

class Product < ApplicationRecord
end

例如,当我插入CheckInDetail 时,我将外键product_id 添加到哈希参数中。我尝试使用一些不存在的产品 ID 和列 product_id 将为空。我想在这样插入时抛出异常。

有一种方法可以在模型上使用validate 在插入之前检查该字段。但我认为这会花费时间(因为我插入了一堆项目)并且不是真正必要的,因为客户不这样做。 (以防万一真的出了问题)。

【问题讨论】:

    标签: ruby-on-rails ruby database activerecord


    【解决方案1】:

    这是关系数据库的好处之一,因为您可以在迁移中添加一个 foreign_key 引用,并且一切都应该正常工作。 您可以使用 rails g migration add_foreign_key_to_check_in_details 运行迁移

    在迁移中,您应该添加如下内容:

    class AddForeignKeyToCheckInDetails < AR::Migration
      def change
        remove_foreign_key :check_in_details, :products
        add_foreign_key :check_in_details, :products, dependent: :delete
      end
    end
    

    有了这个,所有保存不存在产品的尝试都将失败。还要确保将 NOT NULL 约束添加到您的 product_id 列,因为使用 null product_id 保存 check_in_detail 的尝试将成功。迁移的更新如下所示:

    change_column :check_in_details, :product_id, :integer, null: false
    

    如果这回答了你的问题,请告诉我。

    【讨论】:

    • 两者?您的意思是更改列和 add_reference。是的,添加参考可以工作,但不会阻止使用nil product_id 提交。
    • 啊。我明白。非常感谢您的解释:D
    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 2023-03-13
    • 2013-05-24
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多