按ID进行批量更新

时间:2014-08-24 16:16:10

标签: ruby-on-rails batch-updates

在表格中约10,000-20,000个对象。我有大约1000个id条目,您想要更改一个值。怎么做到这一点?我不想每次使用1000次INSERT。我认为这不正确。

P.S。这是一个正常的变体吗?

accounts_closes = Account.where(:alfa_flag => false).pluck(:id)

Account.transaction do
  accounts_closes.each do |account_id|
    Account.connection.execute 'UPDATE accounts SET open = false WHERE id = ' + account_id + ';'
  end
end

1 个答案:

答案 0 :(得分:1)

您可以查看此answer,基本上您应该使用update_all,它为一个表的所有记录构建单个更新查询。如果您只需更新某些记录,则可以在更新前使用 where 并将其链接起来,例如:

Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')

希望它有所帮助。

相关问题