ActiveRecord 5 always subqueries separately from the main request

Can someone explain to me how to fix the following behavior? (ActiveRecord 5.0.1):

subquery = User.where(id: 1); nil
=> nil 
2.3.3 :002 > User.where(id: subquery.select(:id))
D, [2017-04-25T11:08:15.988419 #7822] DEBUG -- :   User Load (1.0ms) SELECT "users"."id" FROM "users" WHERE "users"."id" = $1  [["id", 1]]
D, [2017-04-25T11:08:15.994629 #7822] DEBUG -- :   User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" IN (SELECT "users"."id" FROM "users" WHERE "users"."id" = $1)  [["id", 1]]
=> #<ActiveRecord::Relation []> 

I expect the following behavior (ActiveRecord (4.2.7.1)):

subquery = User.where(id: 1); nil
=> nil 
2.2.5 :002 > User.where(id: subquery.select(:id))
D, [2017-04-25T11:14:16.767247 #8374] DEBUG -- :   User Load (1.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" IN (SELECT "users"."id" FROM "users" WHERE "users"."id" = $1)  [["id", 1]]
=> #<ActiveRecord::Relation []> 

As you can see, in the first example, AR makes a redundant query in the database. I did the following test in the test console and RSpec.

UPD: My Gemfile:

source "https://rubygems.org"

gem "grape"
gem "grape-middleware-logger"
gem "grape-swagger", "~> 0.21.0"
gem "pg"
gem "activerecord", "~> 5.0.1", require: "active_record"
gem "activerecord-import", ">= 0.11.0"
gem "actionmailer", require: "action_mailer"
gem "otr-activerecord"
gem "rack"
gem "rake"
gem "unicorn"
gem "rack-cors", require: "rack/cors"
gem "oj"
gem "rollbar", require: "rollbar/middleware/sinatra"
gem "awesome_print"
gem "composite_primary_keys"
gem "chewy"
gem "typhoeus"
gem "counter_culture"
gem "redis"
gem "hiredis"
gem "redis-namespace"
gem "koala"
gem "vkontakte_api"
gem "kramdown"
gem "rouge"
gem "sidekiq"
gem "sidekiq-limit_fetch"
gem "grocer"
gem "hashie"
gem "carrierwave"
gem "fog"
gem "mini_magick"
gem "geoip2"
gem "maxmind_geoip2"
gem "countries", require: "countries/global"
gem "faye", git: "https://github.com/faye/faye.git"
gem "faye-websocket", git: "https://github.com/faye/faye-websocket-ruby.git"
gem "faye-redis", git: "https://github.com/faye/faye-redis-ruby.git"
gem "thin"
gem "gibbon"
gem "onesignal"
gem "clickatell"
gem "twilio-ruby"
gem "rest-client"
gem "httpclient"
gem "bunny"
gem "yt", "~> 0.28.0"
gem "whenever", require: false
gem "daemons", require: false

group :test do
  gem "rspec"
  gem "database_cleaner"
  gem "factory_girl"
  gem "airborne", require: false
  gem "simplecov", require: false
  gem "faker"
  gem "vcr", require: false
end

group :development do
  gem "capistrano"
  gem "capistrano-rbenv"
  gem "capistrano-bundler"
  gem "capistrano3-unicorn"
  gem "capistrano-sidekiq"
end

group :development, :test do
    gem "bullet"
end
+6
source share

Source: https://habr.com/ru/post/1016748/


All Articles