Search code examples
ruby-on-railssingle-table-inheritancevalidation

Two models, one STI and a Validation


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?


Solution

  • 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
    

    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.