活动记录:具有限制的delete_all

Bra*_*ley 5 activerecord ruby-on-rails-3

试图就是否可以将a delete_all的记录数限制为一个最终答案。

我正在尝试以下方法:

Model.where(:account_id => account).order(:id).limit(1000).delete_all
Run Code Online (Sandbox Code Playgroud)

但它似乎不尊重limit,而是删除了所有Model :account_id => account

我希望它会产生以下结果:

delete from model where account_id = ? order by id limit 1000
Run Code Online (Sandbox Code Playgroud)

使用时这似乎工作正常,destroy_all但我想批量删除。

Ale*_*tie 5

尝试:

Model.delete(Model.where(:account_id => account).order(:id).limit(1000).pluck(:id))
Run Code Online (Sandbox Code Playgroud)


Bra*_*ley 0

ActiveRecord::Base.connection.send(:delete_sql,'delete from table where account_id = <account_id> limit 1000')
Run Code Online (Sandbox Code Playgroud)

您必须使用发送,因为“delete_sql”受到保护,但这是有效的。

我发现删除“order by”也显着加快了速度。

.limit我确实认为 using可以使用destroy_all但不能使用这很奇怪delete_all