1
我剛剛注意到,在具有joins
的查詢上使用.size
或.count
會產生意外的結果。使用activerecord連接後計算對象
User.some_scope.size #=> 10
User.joins(:associations).some_scope.size #=> 10 + associated object count
無論我加入表格,我如何獲得適合範圍的用戶數?
一些實際代碼:
class User < ActiveRecord::Base
has_many :tracking_logs, class_name: "Tracking::Log", dependent: :destroy
end
class Tracking::Log < ActiveRecord::Base
belongs_to :user
end
User.where(created_at: Time.now-1.day..Time.now).size #=> 18
SQL: SELECT COUNT(*) FROM "users" WHERE ("users"."created_at" BETWEEN '2015-05-25 10:40:11.423142' AND '2015-05-26 10:40:11.423741')
User.joins(:tracking_logs).where(created_at: Time.now-1.day..Time.now).size #=> 3188
SQL: SELECT COUNT(*) FROM "users" INNER JOIN "tracking_logs" ON "tracking_logs"."user_id" = "users"."id" WHERE ("users"."created_at" BETWEEN '2015-05-25 10:41:15.260113' AND '2015-05-26 10:41:15.260684')
我希望.size
將只適用於基本模型我呼籲查詢,別的就是混亂。
NB,明確要檢查哪個模型的created_at不會改變結果,例如,
User.joins(:tracking_logs).where(users: { created_at: Time.now-1.day..Time.now }).size #=> 3188
SQL: SELECT COUNT(*) FROM "users" INNER JOIN "tracking_logs" ON "tracking_logs"."user_id" = "users"."id" WHERE ("users"."created_at" BETWEEN '2015-05-25 10:49:29.485508' AND '2015-05-26 10:49:29.486120')
User attributes:
:id => :integer,
:category => :string,
:email => :string,
:created_at => :datetime,
:updated_at => :datetime,
:locale => :string,
:original_email => :text,
:registration_id => :integer,
:first_name => :text,
:login_count => :integer,
:offer_type => :text,
:cid => :string,
:fb_like_status => :integer,
:product_purchases => :text
Tracking::Log attributes:
:id => :integer,
:user_id => :integer,
:tracking_referer_id => :integer,
:to => :string,
:controller_name => :string,
:action_name => :string,
:tracking_activity_id => :integer,
:time_since_last_log => :integer,
:created_at => :datetime,
:updated_at => :datetime
是,同樣的結果。 – Epigene
你能提供一些你的代碼嗎?就像它發生的模型和數據一樣?我似乎無法重現這個問題。 – IngoAlbers
同樣在這裏。你可以嘗試使用'ActiveRecord :: Base.logger = Logger.new(STDOUT)'開啓日誌記錄並顯示爲第一個和第二個查詢生成的SQL嗎? – SkyWriter