Skip to content

Invalid table alias when searching has_one through associations #1227

@mbiang

Description

@mbiang

When searching a 'has_one thought' association, a invalid table alias is used in the SQL query if a search parameter for the cousin object is passed in the params has prior to the parameter for the sibling object.

Here is an example:

class A < ActiveRecord::Base
  belongs_to :b, optional: true
  has_one :c, through: :b
end

class B < ActiveRecord::Base
  has_many :as
  belongs_to :c
end

class C < ActiveRecord::Base
  has_many :bs, dependent: :destroy
  has_many :as, through: :b
end

# the following call will succeed
A.search({b_name_equals: 'B', c_name_equals: 'C'}).result

# the following call will fail with this postgres error:
# ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "bs_as")
# LINE 1: ..."."id" = "bs"."c_id" WHERE ("cs"."name" = 'C' AND "bs_as"."n..

A.search({c_name_equals: 'C', b_name_equals: 'B'}).result


Apparently, when building the query, it first joins on "b" in order to join on "cs" to search c.name, and then it it incorrectly assumes the table alias for "bs" as "bs_as", when it should just be "bs".

Ruby Version: 2.7.3
Rails Version: 6.1.3.2
Ransack Version: 2.4.2
Postgres Version: 10.4
Active Admin Version: 2.9.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions