两种模型,一种是 STI,一种是验证
假设我有两个表——产品和订单。为了简单起见,假设一次只能购买一种产品,因此没有像 order_items 这样的连接表。所以关系是Product有很多订单,Order属于product。因此,product_id是Order表中的一个fk。
产品表是 STI,子类是 A、B、C。
当用户订购子类产品 C 时,必须对订单模型字段 order_details 和 order_status 检查两个特殊验证。对于所有其他产品子类(即 A 和 B),这两个字段可以为零。换句话说,当用户购买 A 和 B 时,不需要对这两个字段运行验证。
我的问题是:
如何在 Order 模型中编写验证(可能是自定义?),以便 Order 模型知道只运行验证对于 ITS 的两个字段——order_details 和 order_status——何时将产品子类 C 的 fk_id 保存到订单表中?
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.
The product table is STI -- with the subclasses being A, B, C.
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.
My question is:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关键是在
Order
模型中添加一个validate
方法来检查具体情况:或者类似的内容。只需检查
validate
中的类型并添加适当的错误即可。我刚刚编写了type_c?
函数。无论您的Product
模型是如何定义的,只需检查类型即可。The key is to add a
validate
method in theOrder
model to check for specifics:Or something along those lines. Just check for the type in
validate
and add the appropriate errors. I just made up thetype_c?
function. Just check the type however yourProduct
model is defined.