activerecord-hackery / ransack

Object-based searching.
https://activerecord-hackery.github.io/ransack/
MIT License
5.69k stars 806 forks source link

SQL aliases are not supported when joining relations - at least with PG #1437

Open Galaxy83 opened 1 year ago

Galaxy83 commented 1 year ago

ActiveRecord(?) adds aliases to queries to handle ambiguity when passing the query as a nested hash: Son.joins(:father).where(father: { age: [50, 51] }).ransack(father_name_eq: 'John') throwing: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: invalid reference....

The workaround is to create an SQL query without the alias so Ransack can be joined: Son.joins(:father).where('fathers.age': [50,51]).ransack(father_name_eq: 'John')

Obviously, this is not a solution.

Need a way to handle aliases.

amiel commented 9 months ago

Hi, this is not a solution, but another workaround for folks running in to this issue.

It works for me to use the nested hash syntax instead of the string syntax as long as the referenced name is the pluralized table name as opposed to the singular relationship name.

# 💥 exception
Son.joins(:father).where(father: { age: [50, 51] }).ransack(father_name_eq: 'John')

# ✅ works
Son.joins(:father).where(fathers: { age: [50, 51] }).ransack(father_name_eq: 'John')