在Java中,我们有批处理执行,如下面的java代码:
Statement statement = null;
statement = connection.createStatement();
statement.addBatch("update people set firstname='John' where id=123");
statement.addBatch("update people set firstname='Eric' where id=456");
statement.addBatch("update people set firstname='May' where id=789");
int[] recordsAffected = statement.executeBatch();如何在rails ActiveRecord中进行相同的操作?
发布于 2015-02-24 12:11:45
你可以试试这个。看来你想要的是什么。
# Updating multiple records:
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)为满足员额要求,翻译为:
people = {
123 => { "firstname" => "John" },
456 => { "firstname" => "Eric" },
789 => { "firstname" => "May" }
}
Person.update(people.keys, people.values)请注意,将上述内容转换为SQL仍然会产生多个查询。
发布于 2021-12-01 08:58:58
感谢Rails 6,您现在可以使用upsert_all方法执行批量更新了。
更多详细信息可在此查阅:https://www.bigbinary.com/blog/bulk-insert-support-in-rails-6
请注意,当数据库是unique_by时,不支持MySQL选项,但是它对Postgresql非常有用。
https://stackoverflow.com/questions/28694498
复制相似问题