rails callback STI
In Ruby on Rails, callbacks are methods that get called at certain moments of an object's life cycle. Single Table Inheritance (STI) is a way to use a single model to represent multiple types of objects that are stored in a single table in the database. Here's an example of using callbacks with STI in Rails:
Step 1: Define the parent class with the callback
class Parent < ApplicationRecord
before_save :do_something
def do_something
# Code for the callback action
end
end
Step 2: Create child classes inheriting from the parent class
class Child1 < Parent
# Child1-specific code
end
class Child2 < Parent
# Child2-specific code
end
Step 3: Implement specific behavior in child classes
class Child1 < Parent
def do_something
# Override the callback for Child1
# Code specific to Child1
end
end
class Child2 < Parent
# No specific callback defined, will use Parent's callback
end
Explanation:
- The Parent
class defines a before_save
callback using before_save :do_something
.
- do_something
is a method that will be executed before saving any instance of Parent
or its child classes.
- Child1
and Child2
classes inherit from Parent
.
- Child1
overrides the do_something
method to provide its own implementation for the callback.
- Child2
does not define its own do_something
method, so it will use the do_something
method defined in the Parent
class due to inheritance.