使用 default_scope 之外的外键创建 ActiveRecord 会引发验证错误

问题描述

使用 warehouse_x (foreign key to Warehouse table) 创建超出 default_scope 的产品,即仓库_x 具有 warehouse_type **damage**

无法创建记录并抛出错误

ActiveRecord::RecordInvalid: Validation Failed: Warehouse must exist

架构

create_table "product",force: :cascade do |t|
    t.float "unit_price"
    t.bigint "warehouse_id",null: false

    ...

    t.index ["warehouse_id"],name: "index_stock_details_on_warehouse_id"
  end

create_table "warehouses",force: :cascade do |t|
    t.string "warehouse_name"

    ...

    t.integer "warehouse_type",default: 0
  end

仓库模型(warehouse.rb)

class Warehouse < ApplicationRecord
  has_many :products

  default_scope {where(warehouse_type: :ok_product)}

  scope :damaged,-> {unscoped.where(warehouse_type: :damage)}

  enum warehouse_type: {
    ok_product: 0,damage_product: 2
  }

end

产品模型(product.rb)

class Product < ApplicationRecord
    belongs_to :warehouse
end

如何使用认外键(关系表)创建记录。

解决方法

验证是否由您的belongs_to 关联生成,您可以像这样禁用:

class Product < ApplicationRecord
  belongs_to :warehouse,optional: true
end