Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ActiveRecord's .where cannot handle polymorphic arrays containing different types #17011

Closed
pvande opened this issue Sep 22, 2014 · 4 comments · Fixed by #22365
Closed

ActiveRecord's .where cannot handle polymorphic arrays containing different types #17011

pvande opened this issue Sep 22, 2014 · 4 comments · Fixed by #22365

Comments

@pvande
Copy link

pvande commented Sep 22, 2014

Example: https://gist.github.com/pvande/2e346213ace076cd0edb

ActiveRecord supports filtering on a polymorphic association, including filtering on an array of related objects, permitting users to write queries like this:

PriceEstimate.where(estimate_of: [treasure1, treasure2]).count

This generally works pretty well, generating an SQL query like this:

SELECT COUNT(*)
FROM "price_estimates"
WHERE (
  "price_estimates"."estimate_of_type" = 'Treasure' AND
  "price_estimates"."estimate_of_id" IN (1, 2)
)

When attempting such a query with multiple related types however, the query breaks down.

# Both Parrot and Pirate are valid polymorphic types for Treasure
parrot, pirate = Parrot.find(1), Pirate.find(1)
Treasure.where(looter: [parrot, pirate]).count
SELECT COUNT(*)
FROM "treasures"
WHERE (
  "treasures"."looter_type" = 'Parrot' AND
  "treasures"."looter_id" IN (1, 1)
)

The expected result for the above query would include all Treasure looted by either Parrot#1 or Pirate#1.

@pvande
Copy link
Author

pvande commented Sep 22, 2014

I have a patch together for this issue, but I'm waiting to submit it since it relies in part on #17010.

@rails-bot
Copy link

This issue has been automatically marked as stale because it has not been commented on for at least
three months.

The resources of the Rails team are limited, and so we are asking for your help.

If you can still reproduce this error on the 4-2-stable, 4-1-stable branches or on master,
please reply with all of the information you have about it in order to keep the issue open.

Thank you for all your contributions.

@brchristian
Copy link
Contributor

I and others am having issues that appear to be stemming from this, as discussed in spree/spree#6213

@kddnewton
Copy link
Contributor

Should have looked here first, but I also worked on this:
https://github.com/rails/rails/compare/master...kddeisz:fix_polymorphic_different_classes_where?expand=1

Not sure if my work is helpful to you @phuibonhoa but I figured I'd put it here/bump this issue anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
5 participants