Two models, one STI and a Validation

孤人 提交于 2019-12-21 05:37:32

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/2561316/two-models-one-sti-and-a-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!