0

Given the following code

class Things < ActiveRecord::Base
  belongs_to :user
  belongs_to :sock
end

class User < ActiveRecord::Base
  has_many :things
  has_many :socks, through: :things
end

class Sock < ActiveRecord::Base
  has_many :things
  has_many :users, through: :things
end

Assuming the first user has two socks and all other users have one sock. There are 1000 users in total and 1001 socks in total. You would expect find_in_batches to return the same number of records as a normal select.

User.joins(:socks).count
=> 1001
agg = []
User.joins(:socks).find_in_batches{|g| agg += g}
agg.count
=> 1000
4

1 に答える 1

2

find_in_batches主キーを使用して結果の検索を開始する場所を決定するため、関係の反対側から移動する必要があります (SELECT ... FROM ... WHERE id > N LIMIT 1000)。

Sock.joins(:users).count
=> 1001
agg = []
Sock.joins(:users).find_in_batches{|g| agg += g}
agg.count
=> 1001
于 2013-03-27T19:41:34.727 に答える