Rails Single Table Inheiritance and class loading

I might have mentioned this before but you should be very aware of how your development environment loads and caches STI classes.

Update: yeah, I did mention this before.

Say I have:


class Partner
end

class DrivingSchool < Partner
end

class Library < Partner
end

and I want to query

Partner.find_by_partner_code("abcde")

unless the system has previously loaded DrivingSchool and Library it will not query those subtypes.

You’ll get

SELECT * from Partner WHERE type = "Partner" AND partner_code = 'abcde'

rather than

SELECT * from Partner WHERE type = "Partner" OR type = 'DrivingSchool' OR type = 'Library' AND partner_code = 'abcde'

and so those subtypes you want to include don’t come through.

The solution is to add the following to your ApplicationController.


# We're using STI here and it doesn't do a great job of loading up subtypes
# so if the system hasn't yet seen a subtype of Partner and you then query
# on Partner, it won't find subtypes.
require_dependency 'partner'
require_dependency 'library'
require_dependency 'driving_school'

Leave a Reply