Skip to content

Commit

Permalink
add polymorphic type support for virtual delegates
Browse files Browse the repository at this point in the history
  • Loading branch information
kbrock committed Sep 1, 2020
1 parent 42f0d5f commit 324552b
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/active_record/virtual_attributes/virtual_delegates.rb
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,21 @@ def self.select_from_alias(to_ref, col, to_model_col_name, src_model_id)
to_ref.klass.all
end

src_model = to_ref.active_record
to_table = select_from_alias_table(to_ref.klass, src_model_id.relation)
to_model_id = to_ref.klass.arel_attribute(to_model_col_name, to_table)
to_column = to_ref.klass.arel_attribute(col, to_table)
arel = query.except(:select).select(to_column).arel
.from(to_table)
.where(to_model_id.eq(src_model_id))

# :type is in the reflection definition (meaning it is polymorphic)
if to_ref.type
# get the class name (e.g. "Host")
polymorphic_type = src_model.base_class.name
arel = arel.where(to_ref.klass.arel_attribute(to_ref.type).eq(polymorphic_type))
end

yield arel if block_given?

Arel.sql("(#{arel.to_sql})")
Expand Down

0 comments on commit 324552b

Please sign in to comment.