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