【问题标题】:Is there anything like batch update in Rails?Rails 中是否有类似批量更新的功能?
【发布时间】:2015-02-24 11:23:10
【问题描述】:

在 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 中做同样的事情?

【问题讨论】:

  • 例如,我有一个名为 User 的表,它有列点。我有这个值 IDs[1,2,3,9,10,15,20] 对应的 Points[2,3,5,1,1,5,5] 要在数据库中一次更新。就像更新用户设置点 = (2,3,5,1,1,5,5) 其中用户 ID = (1,2,3,9,10,15,20) 但这不是正确的 sql 命令。

标签: mysql ruby-on-rails


【解决方案1】:

你可以试试这个。看起来像你所追求的。

# Updating multiple records:
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)

引用:https://cbabhusal.wordpress.com/2015/01/03/updating-multiple-records-at-the-same-time-rails-activerecord/

为了符合岗位要求,翻译为:

people = { 
  123 => { "firstname" => "John" },
  456 => { "firstname" => "Eric" },
  789 => { "firstname" => "May" }
}
Person.update(people.keys, people.values)

请注意,将上述内容翻译成 SQL 仍会产生多个查询

【讨论】:

  • 非常感谢这是我需要的。
  • 也教会了我一些东西
  • 感谢您发布您的答案!请注意,您应该在此处、此站点上发布答案的基本部分,否则您的帖子有被删除的风险See the FAQ where it mentions answers that are 'barely more than a link'. 如果您愿意,您仍然可以包含该链接,但仅作为“参考”。答案应该是独立的,不需要链接。
【解决方案2】:

感谢Rails 6,您现在可以使用upsert_all 方法进行批量更新,例如。

更多详情请点击:https://www.bigbinary.com/blog/bulk-insert-support-in-rails-6

请注意,当数据库是 MySQL 时不支持 unique_by 选项,但它适用于 Postgresql。

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 2012-08-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多