STI joins

I have 2 models set up using single table inheritance (STI) with belongs_to relationships to a third model.

class CoveredEntity < Entity
  belongs_to :breach
    ...
end

class BusinessAssociate < Entity
  belongs_to :breach
    ...
end

class Breach < ActiveRecord::Base
  has_one :covered_entity
  has_one :business_associate
end

In my index view for breaches controller I am displaying the covered_entity.name and the business_associate.name (if it exists). I want to allow the users to sort the index table by either of these values; however, since they use STI and are the same table, just doing @breaches.includes(:covered_entity).includes(:business_associate).order("#{sort_column} #{sort_direction}") does not work.

I can get around this by using .joins("inner join (select * from entities where entities.type = 'CoveredEntity') as covered_entities left join (select * from entities where entities.type = 'BusinessAssociate') as business_associates) and then I am able to use .order("business_associate.name") or .order("covered_entities.name") and get the desired results.

I was curious if there is another way to do this that would not require me to write out the joins by hand ( passing an alias to association or includes for example).

Any reason why you can’t use something like this?

sort_by_name_of = use_business_entity ? :business_associate : :covered_entity
@breaches = @breaches.joins(sort_by_name_of).order(:name) if sort_by_name

works in my quick, test rails 3.0.7 app

Is using #joins abhorrent to you?

Also, as an aside, any reason you don’t/can’t put your “belongs_to :breach” relationship in your Entity class (since both STI sub-types both have the relationship of the same name)?