wvanbergen / scoped_search

Easily search you ActiveRecord models with a simple query language that converts to SQL.
MIT License
265 stars 78 forks source link

Problems searching for resources belonging to STI #180

Open adamruzicka opened 6 years ago

adamruzicka commented 6 years ago

Let's consider classes Location and Organization which are subclasses of Placement using STI. Class Item belongs_to one organization and one location. Searching for an Item belonging to organization and location generates wrong search query and always returns 0 items.

The search query first LEFT OUTER JOINs the placements, then LEFT OUTER JOINs the placements again with an alias, but when the filtering is done, the first joined table is used twice instead of each being used once.

# Running this
Item.search_for('location = Somewhere and organization = Something').count

# Generates this SQL
SELECT COUNT(DISTINCT "items"."id") FROM "items"
  LEFT OUTER JOIN "placements" ON "placements"."id" = "items"."location_id" AND "placements"."type" IN ('Location')
  LEFT OUTER JOIN "placements" "organizations_items" ON "organizations_items"."id" = "items"."organization_id" AND "organizations_items"."type" IN ('Organization')
     WHERE ((("placements"."title" = 'Somewhere') AND ("placements"."title" = 'Something')))

Example rails application demonstrating the issue can be found at adamruzicka/scoped_search_reproducer.

Versions used: