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



使用默认范围之外的warehouse_x (foreign key to Warehouse table)创建产品,即仓库_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

相关内容

  • 没有找到相关文章

最新更新