In case this is of use to anybody here is what I did to use STI and
validate the contents of column type…
I have a users table with a column named ‘type’ to implement STI and.
The Admin should be the only one being able to maintain the table. My
model was running validations on the contents of type but my ‘edit’
page was not returning the value of the column. I tried and tried but
nothing would work.
What I ended up doing was to create an alias attribute in my model:
class User < ActiveRecord::Base
alias_attribute :category, :type
What the method ‘alias_attribute’ is doing is create a virtual
attribute called ‘category’ that is tied to the attribute ‘type’.
Whatever happens to one also happens to the other, which means that
you can now use ‘category’ in your code and neither Ruby nor Rails
will complain or “ignore” the column.
I then replaced the use of ‘type’ with ‘category’ in all my code and
everything worked like a charm. I also changed the labels in all pages
from ‘Type’ to ‘Category’ for consistency and because the built in
validations (such as ‘validates_presence_of’) use the column name in
the error messages. Keeping ‘Type’ as a label could be confusing to
the users when the error returned says ‘Category cannot be blank’.
Now the STI is still in place, through the use of ‘type’, but I can
also easily work with the column value by using ‘category’.
If you want to do the same but still keep the label ‘Type’ (or
whatever you chose as column label) in your app. you can use the
plugin ‘custom-err-msg’, which allows you to override the column name.