ransack icon indicating copy to clipboard operation
ransack copied to clipboard

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

Open Galaxy83 opened this issue 1 year ago • 1 comments

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.

Galaxy83 avatar Sep 07 '23 09:09 Galaxy83

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

amiel avatar Feb 01 '24 15:02 amiel