0

使用它创建一个产品,warehouse_x (foreign key to Warehouse table)它在 default_scope 之外,即 warehouse_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

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

4

1 回答 1

0

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

class Product < ApplicationRecord
  belongs_to :warehouse, optional: true
end
于 2021-07-22T14:51:19.203 回答