Brian Carmicle
Brian Carmicle

Reputation: 95

Overriding an inherited after_save function in ActiveRecord

Suppose I have an Active Record class, with an after_save method, e.g.:

class Vehicle < ActiveRecord::Base
  after_save :wheel_count

  def wheel_count
    puts 4

(I'm aware this is poor design; it's just an example)

And I have a subclass of this class, with which I want to override the after_save method:

class Boat < Vehicle
  def wheel_count
    puts 0

However, it seems that the child function doesn't get called. Is there a way to have the after_save function be dynamically chosen based on the instance? I imagine I could do something along the lines of:

after_save :after_save_handler

def after_save_handler
  wheel_count

but this seems like a poor solution.

Upvotes: 0

Views: 219

Answers (1)

Gautam
Gautam

Reputation: 1812

You can do this using STI or Single Table Inheritance.

Active Record allows inheritance by storing the name of the class in a column that by default is named “type” (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this:

class Company < ActiveRecord::Base; end
class Firm < Company; end
class Client < Company; end
class PriorityClient < Client; end

When you do Firm.create(name: "37signals"), this record will be saved in the companies table with type = “Firm”. You can then fetch this row again using Company.where(name: '37signals').first and it will return a Firm object.

You can easily override the parent class methods in the child class and when those methods are called, they respond based on the type of object. You can read in detail over here - Single Table Inheritance

Upvotes: 2

Related Questions