4

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?

keruilin
  • 14,638
  • 30
  • 103
  • 172
  • Is there an alternative to using polymorphism here? – keruilin Apr 02 '10 at 11:18
  • yeah... see my edits again :) It just dawned on my what you were really after. With future questions it might be better to include the actual model code. Would have helped me out from the onset (then again I was all over the place so it may have been just me :) – Tony Fontenot Apr 02 '10 at 13:08
  • yea, don't think it's you! it was my original prob statement. thx for help working through. – keruilin Apr 02 '10 at 13:53

1 Answers1

4

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.

Tony Fontenot
  • 4,981
  • 1
  • 19
  • 19