How to cast an ActiveRecord object to another class when using STI?

You shouldn't need to cast since Ruby does not perform any type-checking at compile time. What are you trying to accomplish?

Say you have a class Dad, and child classes Son and Daughter.

You could just have a variable @dad and store in it either a Son or Daughter object, and just treat it as if it were a Dad. As long as they respond to the same methods, it makes no difference. This is a concept called "duck typing".


If we have something like following

class A < ApplicationRecord
end

Class B < A
end

we can use becomes

a = A.first
b = a.becomes(B)

or vice versa


#becomes is what you are looking for:

http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-becomes