iTake
iTake

Reputation: 315

Single Table Inheritance with validation ruby on rails

If I have models like this:

class Transaction < ActiveRecord
    # create table called transactions and add type column to it.  
    # add common methods inside this class
end

class CashTransaction < Transaction
     # the type column will be CashTransaction and used to determine entry for this class in transactions table 
end

class CreditCardTransaction < Transaction
    validates :settled, :presence => true
    # the type column will be CreditCardTransaction and used to determine entry for this class in  transactions table 
end

How can I apply validation that is unique to the CreditCardTransaction? So parent class Transaction and CashTransaction do not need validation on whether the transaction was settled?

Upvotes: 0

Views: 2088

Answers (2)

Substantial
Substantial

Reputation: 6682

Your example code is correct.

In Rails 3, validations called in a subclass will apply to an instance of that subclass only (in addition to superclass validations). Superclass validations apply to all subclasses.

Remember to only work with subclasses when using STI. In other words, never instantiate the superclass for any reason. Doing so will interfere with Rails' internal STI magic sauce, leaving you with unexpected behavior and ugly hacks to get things working again.

Upvotes: 2

Bob
Bob

Reputation: 2121

Hm...I think you have an column indicating that this is CreditCardTransation. So you can use validator inside a scope:

Rails 3 Validation with Scope Conditions

Upvotes: 0

Related Questions