【问题标题】:Update multiple records simultaneously with ActiveRecord in Rails using one query?使用一个查询在 Rails 中使用 ActiveRecord 同时更新多条记录?
【发布时间】:2010-12-15 22:11:50
【问题描述】:

假设我的 Rails 应用程序中有一个名为“user_products”的表和一个名为 UserProduct 的相应模型。我的表中还有一个名为“is_temporary”的字段。现在假设我想运行这样的查询,但使用 ActiveRecord 抽象层:

UPDATE user_products SET is_temporary = false WHERE user_id = 12345;

有没有办法使用 ActiveRecord 来做到这一点?也许类似于

UserProduct.find_by_user_id(12345).update_attributes(:is_temporary => false)

我希望只运行一个查询来实现这一点。

【问题讨论】:

    标签: ruby-on-rails orm activerecord


    【解决方案1】:

    这是一个旧帖子。我更新了这个以防有人检查它:)(Rails 4)

    DEPRECATION: Relation#update_all with conditions is deprecated. Please use Item.where(color: 'red').update_all(...) rather than Item.update_all(..., color: 'red').
    

    所以查询将是

    UserProduct.where(:user_id => 12345).update_all(:is_temporary => false)
    

    干杯

    【讨论】:

    • 是否可以在update_all中传递数组,进行一一对应的更新。 UserProduct.where(:user_id => [1,2,3,4,5]).update_all(:name => ["ball", "bat", "shelf", "boots", "net"]).
    【解决方案2】:
    UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})
    

    但请注意:这会跳过所有验证和回调,因为不会实例化任何 UserProduct 实例。

    【讨论】:

      【解决方案3】:
      UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})
      

      【讨论】:

      • 已弃用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2021-11-26
      • 2021-09-22
      • 1970-01-01
      • 2013-12-13
      • 2017-01-03
      • 1970-01-01
      相关资源
      最近更新 更多