跳到內容 跳到搜尋
方法
B
D
E
T
U
包含的模組

屬性

[R] finish

BatchEnumerator 結束的主索引鍵值,含這個值。

[R] relation

BatchEnumerator 產生分批結果的關聯。

[R] start

BatchEnumerator 開始的主索引鍵值,含這個值。

公開實例方法

batch_size()

BatchEnumerator 產生分批結果的區塊大小。

# File activerecord/lib/active_record/relation/batches/batch_enumerator.rb, line 28
def batch_size
  @of
end

delete_all()

分批刪除記錄。回傳受影響的總列數。

Person.in_batches.delete_all

有關如何刪除每批記錄的詳細資訊,請參閱 Relation#delete_all

# File activerecord/lib/active_record/relation/batches/batch_enumerator.rb, line 66
def delete_all
  sum(&:delete_all)
end

destroy_all()

分批銷毀記錄。回傳受影響的總列數。

Person.where("age < 10").in_batches.destroy_all

有關如何銷毀每批記錄的詳細資訊,請參閱 Relation#destroy_all

# File activerecord/lib/active_record/relation/batches/batch_enumerator.rb, line 97
def destroy_all
  sum do |relation|
    relation.destroy_all.count(&:destroyed?)
  end
end

each(&block)

為每批記錄產生 ActiveRecord::Relation 物件。

Person.in_batches.each do |relation|
  relation.update_all(awesome: true)
end
# File activerecord/lib/active_record/relation/batches/batch_enumerator.rb, line 108
def each(&block)
  enum = @relation.to_enum(:in_batches, of: @of, start: @start, finish: @finish, load: false, cursor: @cursor, order: @order, use_ranges: @use_ranges)
  return enum.each(&block) if block_given?
  enum
end

each_record(&block)

從資料庫中循序一個記錄集合(例如,使用 all 方法)是非常低效率的,因為它會嘗試立刻實體化所有物件。

這種情況下,分批處理方法允許您分批處理記錄,從而大幅降低記憶體消耗。

Person.in_batches.each_record do |person|
  person.do_awesome_stuff
end

Person.where("age > 21").in_batches(of: 10).each_record do |person|
  person.party_all_night!
end

如果您沒有在 each_record 中提供區塊,它會回傳列舉項以供與其他方法串接

Person.in_batches.each_record.with_index do |person, index|
  person.award_trophy(index + 1)
end
# File activerecord/lib/active_record/relation/batches/batch_enumerator.rb, line 53
def each_record(&block)
  return to_enum(:each_record) unless block_given?

  @relation.to_enum(:in_batches, of: @of, start: @start, finish: @finish, load: true, cursor: @cursor, order: @order).each do |relation|
    relation.records.each(&block)
  end
end

touch_all(...)

以批次觸及紀錄。傳回受影響總列數。

Person.in_batches.touch_all

參閱 Relation#touch_all,以了解如何觸及每個批次。

# File activerecord/lib/active_record/relation/batches/batch_enumerator.rb, line 86
def touch_all(...)
  sum do |relation|
    relation.touch_all(...)
  end
end

update_all(updates)

以批次更新紀錄。傳回受影響總列數。

Person.in_batches.update_all("age = age + 1")

參閱 Relation#update_all,以了解如何更新每個批次。

# File activerecord/lib/active_record/relation/batches/batch_enumerator.rb, line 75
def update_all(updates)
  sum do |relation|
    relation.update_all(updates)
  end
end