gpt4 book ai didi

ruby-on-rails - 使用一个查询在 Rails 中使用 ActiveRecord 同时更新多条记录?

转载 作者:行者123 更新时间:2023-12-03 21:01:43 25 4
gpt4 key购买 nike

假设我的 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)

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

最佳答案

这是一个旧帖子。我更新了这个以防有人检查它:)(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)

干杯

关于ruby-on-rails - 使用一个查询在 Rails 中使用 ActiveRecord 同时更新多条记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4455479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com