diff --git a/lib/pg_search/scope_options.rb b/lib/pg_search/scope_options.rb index ab5db372..a4d2397d 100644 --- a/lib/pg_search/scope_options.rb +++ b/lib/pg_search/scope_options.rb @@ -164,7 +164,13 @@ def rank end def rank_join(rank_table_alias) - "INNER JOIN (#{subquery.to_sql}) AS #{rank_table_alias} ON #{primary_key} = #{rank_table_alias}.pg_search_id" + arel_table = model.arel_table + subquery_arel = subquery.arel.as(rank_table_alias) + + arel_table + .join(subquery_arel) + .on(arel_table[model.primary_key].eq(subquery_arel[:pg_search_id])) + .join_sources end def include_table_aliasing_for_rank(scope) diff --git a/spec/integration/pg_search_spec.rb b/spec/integration/pg_search_spec.rb index 9864ba88..7790dd15 100644 --- a/spec/integration/pg_search_spec.rb +++ b/spec/integration/pg_search_spec.rb @@ -1088,6 +1088,10 @@ it "finds by a combination of the two" do expect(Post.search_by_content_with_tsvector("phooey commentone").map(&:id)).to eq([expected.id]) end + + it "finds by the tsvector column when using order" do + expect(Post.search_by_content_with_tsvector("phooey").order("#{Post.table_name}.id").map(&:id)).to eq([expected.id]) + end end context "when using multiple tsvector columns" do