Two models, one STI and a Validation

Posted by keruilin on Stack Overflow See other posts from Stack Overflow or by keruilin
Published on 2010-04-01T14:59:26Z Indexed on 2010/04/01 15:03 UTC
Read the original article Hit count: 303

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 the two fields -- order_details and order_status -- when Product subclass C is being saved to the orders table?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about validations