微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。