squeel icon indicating copy to clipboard operation
squeel copied to clipboard

Subquery generation when using a Relation as a parameter in regular where()

Open gamov opened this issue 9 years ago • 4 comments

I've noticed that in my updated app, subqueries are generated when I supply a relation in a regular where():

Draft.where(id: Draft.limit(2)) 
# => SELECT "drafts".* FROM "drafts" WHERE "drafts"."id" IN (SELECT "drafts"."id" FROM "drafts" LIMIT 2)

This introduces a subquery instead of standard Rails array of ids:

# => SELECT "drafts".* FROM "drafts" WHERE "drafts"."id" IN (1,2)

IMO, Squeel should only work this kind of magic inside a where{} block.

gamov avatar Feb 23 '16 10:02 gamov

Could you post your Gemfile.lock? ( or at relevant gem info, Active Record, Squeel, etc )

mckinnsb avatar Feb 26 '16 14:02 mckinnsb

Of course! Do you think it's the standard behaviour?

activerecord (4.0.13)
  activemodel (= 4.0.13)
  activerecord-deprecated_finders (~> 1.0.2)
  activesupport (= 4.0.13)
  arel (~> 4.0.0)
arel (4.0.2)
  arel-helpers (2.2.0)
  activerecord (>= 3.1.0, < 5)
ransack (1.6.5)
  actionpack (>= 3.0)
  activerecord (>= 3.0)
  activesupport (>= 3.0)
  i18n
  polyamorous (~> 1.1)
squeel (1.2.3)
  activerecord (>= 3.0)
  activesupport (>= 3.0)
  polyamorous (~> 1.1.0)

PS: I removed the information about the update since I could also see it under Rails 3.2 -> (Rails 4.0), forgot the 'updated' word...

gamov avatar Feb 29 '16 08:02 gamov

:+1: for this issue, it breaks existing complex subquery in Rails 4 application

kimrgrey avatar Mar 01 '16 13:03 kimrgrey

I'm pretty sure this is standard behavior, see: https://github.com/activerecord-hackery/squeel/issues/272 for examples of expected behavior re: subqueries and Rails.

If you need "id" IN (1,2), I think I would just .to_a.map &:id ( or perhaps just to_a would give you what you want, maybe the magic is in recognizing that you passed an CollectionProxy ).

mckinnsb avatar Mar 01 '16 14:03 mckinnsb