diff --git a/lib/has_aux_table/util.rb b/lib/has_aux_table/util.rb index 8a70d0e..92bdae9 100644 --- a/lib/has_aux_table/util.rb +++ b/lib/has_aux_table/util.rb @@ -107,7 +107,7 @@ module HasAuxTable all_predicates = T.cast( relation.where_clause.instance_variable_get(:@predicates), - T::Array[Arel::Nodes::Binary] + T::Array[T.any(Arel::Nodes::Binary, Arel::Nodes::HomogeneousIn)] ) filtered_predicates = @@ -132,13 +132,20 @@ module HasAuxTable if all_on_aux_table # the eager load generates a join which creates table alias nodes on attributes instead # of the original table, so we need to replace those with the original table - filtered_predicates.each do |node| - if (attribute = node.left) && (table_alias = attribute.relation) && - table_alias.is_a?(Arel::Nodes::TableAlias) - attribute.relation = table_alias.left + filtered_predicates.map! do |node| + if node.left&.relation&.is_a?(Arel::Nodes::TableAlias) + left = node.left.dup + left.relation = left.relation.left + node = node.dup + case node + when Arel::Nodes::HomogeneousIn + node.instance_variable_set(:@attribute, left) + when Arel::Nodes::Binary + node.instance_variable_set(:@left, left) + end end + node end - filtered_predicates else nil diff --git a/spec/has_aux_table_spec.rb b/spec/has_aux_table_spec.rb index ebe5898..36a76eb 100644 --- a/spec/has_aux_table_spec.rb +++ b/spec/has_aux_table_spec.rb @@ -371,6 +371,12 @@ RSpec.describe HasAuxTable do expect(car_names).to eq(["Tesla Model 3", "Toyota Prius"]) end + it "works when using the same relation mulitiple times" do + cars = Car.where(fuel_type: %w[hybrid electric]) + expect(cars.count).to eq(2) + expect(cars.find_by(name: "Toyota Prius").fuel_type).to eq("hybrid") + end + it "doesn't add joins for queries without auxiliary columns" do toyota_cars = Car.where(name: "Toyota Prius") expect(toyota_cars.length).to eq(1)