For single table inheritance, how do you force Rails to use an integer column for the 'type' column instead of string?
Asked
Active
Viewed 864 times
0
-
1It's my experience that when you start putting your fingers so deep into the internals is that you usually eventually wish you didn't – bbozo Dec 01 '15 at 16:46
2 Answers
1
You can override the methods Rails uses to convert the table name to class name and vice versa:
The relevant methods are find_sti_class
which is responsible for the translating the value stored in the type column to the respective ActiveRecord model and sti_name
which is responsible for retriving the value stored in type column given an ActiveRecord subclass.
You can override them like this:
class Institution::Base < ActiveRecord::Base
ALLOWED_CLASSES = %w[Institution::NonProfit Institution::Commercial]
class << self
def find_sti_class type_name
idx = type_name.to_i
super if idx == 0
ALLOWED_CLASSES[idx-1].constantize
rescue NameError, TypeError
super
end
def sti_name
idx = ALLOWED_CLASSES.index(self.name)
if idx.nil?
super
else
idx + 1
end
end
end
end
I have written a post elaborating this in more detail.

lorefnon
- 12,875
- 6
- 61
- 93
0
You would have to find the part of ActiveRecord responsible for handling the "type" column and monkey patch it, i.e. override how it worked from within your application.

John Topley
- 113,588
- 46
- 195
- 237