4

假设我有两个表——产品和订单。为简单起见,假设一次只能购买一种产品,因此没有像 order_items 这样的连接表。所以关系是Product有很多订单,而Order属于产品。因此,product_id 是 Order 表中的一个 fk。

产品表是 STI——子类是 A、B、C。

当用户订购子类产品 C 时,必须在订单模型字段 order_details 和 order_status 上检查两个特殊验证。对于所有其他 Product 子类(即 A 和 B),这两个字段可以为 nil。换句话说,当用户购买 A 和 B 时,不需要对这两个字段进行验证。

我的问题是:

我如何在 Order 模型中编写验证(可能是自定义的?),以便当 Product 子类 C 的 fk_id 保存到订单表时,Order 模型知道只运行 ITS 两个字段的验证 - order_details 和 order_status ?

4

1 回答 1

4

关键是validate在模型中添加一个方法Order来检查细节:

  def validate
    if product and product.type_c?
      errors.add(:order_details, "can't be blank") if order_details.blank?
      # any other validations
    end
  end

或类似的规定。只需检查输入validate并添加适当的错误。我只是弥补了这个type_c?功能。只需检查类型,但您的Product模型已定义。

于 2010-04-01T19:27:22.963 回答