两个模型,一个STI和一个validation

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

产品表是STI – 子类是A,B,C。

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

我的问题是:

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

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

  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? function。 只需检查类型,然后定义Product型号。