STI type value mapping

22 views
Skip to first unread message

byrnejb

unread,
Nov 6, 2015, 11:45:56 AM11/6/15
to Ruby on Rails: Talk
I have never used STI with AR but I am now considering it.  My question has to do with the Base.inheritance_column.  According to the api docs:

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).

Can one assign a value within the subclass to use in the  inheritance_column in place of the class name?  For example, given:

class Transaction < ActiveRecord::Base
end
class ArClientInvoice < Transaction
end

Is there any way to arbitrarily set ArClientInvoice.type to "ARIN" for all occurrences and to have Active record use this for STI purposes in place of "
ar_client_invoice"?  The use case for this is for compatibility with a non-Rails application. 

The simple answer is to rename the class to
ARIN < ActiveRecord::Base

and to add inflect.acronym 'ARIN' in config/initializers/inflections.rb.  Or I could create a separate column which always gets initialised and locked to 'ARIN' in ArClientInvoice and then pass that to the external application. But I was sort of hoping that there would be a way to have my class name and pass ARIN as the type too.

byrnejb

unread,
Nov 6, 2015, 11:56:37 AM11/6/15
to Ruby on Rails: Talk
I had previously found this method referred to in an older API document but it was marked as being deprecated/removed in later version of Rails.  
Does this still work and if so is it going to be removed or replaced with something else?


# File activerecord/lib/active_record/inheritance.rb, line 134
def sti_name
  store_full_sti_class ? name : name.demodulize
end

Reply all
Reply to author
Forward
0 new messages