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?
The key is to add a
validatemethod in theOrdermodel to check for specifics:Or something along those lines. Just check for the type in
validateand add the appropriate errors. I just made up thetype_c?function. Just check the type however yourProductmodel is defined.