两种模型,一种 STI 和一种验证 [英] Two models, one STI and a Validation
问题描述
假设我有两个表——Products 和 Orders.为简单起见,假设一次只能购买一种产品,因此没有像 order_items 这样的连接表.所以关系是Product有很多个订单,Order属于product.因此,product_id 是 Order 表中的一个 fk.
Let's say I have two tables -- Products and Orders. For the sake of simplicity assume that only one product can be purchased at a time so there is no join table like order_items. So the relationship is that Product has many orders, and Order belongs to product. Therefore, product_id is a fk in the Order table.
产品表为 STI -- 子类为 A、B、C.
The product table is STI -- with the subclasses being A, B, C.
当用户订购子类产品 C 时,必须检查订单模型字段 order_details 和 order_status 上的两个特殊验证.对于所有其他产品子类(即 A 和 B),这两个字段可以为零.换句话说,当用户购买 A 和 B 时,不需要对这两个字段运行验证.
When the user orders subclass Product C, two special validations must be checked on the Order model fields order_details and order_status. These two fields can be nil for all other Product subclasses (ie A and B). In other words, no validation needs to run for these two fields when a user purchases A and B.
我的问题是:
如何在 Order 模型中编写验证(可能是自定义的?),以便 Order 模型知道只对 ITS 两个字段(order_details 和 order_status)运行验证,当将产品子类 C 的 fk_id 保存到订单表?
How do I write validations (perhaps custom?) in the Order model so that the Order model knows to only run the validations for ITS two fields -- order_details and order_status -- when the fk_id to Product subclass C is being saved to the orders table?
推荐答案
关键是在Order
模型中添加一个validate
方法来检查细节:>
The key is to add a validate
method in the Order
model to check for specifics:
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
模型已定义.
Or something along those lines. Just check for the type in validate
and add the appropriate errors. I just made up the type_c?
function. Just check the type however your Product
model is defined.
这篇关于两种模型,一种 STI 和一种验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!