在 rails 中一次更新多条记录 [英] Updating several records at once in rails

查看:40
本文介绍了在 rails 中一次更新多条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在构建的 rails 2 应用程序中,我需要更新具有特定属性的记录集合.我有一个命名范围来查找集合,但我必须遍历每条记录以更新属性.我必须进行数千次查询,而不是进行一次查询来更新数千条记录.

In a rails 2 app I'm building, I have a need to update a collection of records with specific attributes. I have a named scope to find the collection, but I have to iterate over each record to update the attributes. Instead of making one query to update several thousand records, I'll have to make several thousand queries.

到目前为止我发现的是类似于 Model.find_by_sql("UPDATE products ...)

What I've found so far is something like Model.find_by_sql("UPDATE products ...)

这感觉真的很初级,但我用谷歌搜索并环顾四周,但没有找到我的答案.

This feels really junior, but I've googled and looked around SO and haven't found my answer.

为了清楚起见,我所拥有的是:

For clarity, what I have is:

ps = Product.last_day_of_freshness
ps.each { |p| p.update_attributes(:stale => true) }

我想要的是:

Product.last_day_of_freshness.update_attributes(:stale => true)

推荐答案

听起来您正在寻找 ActiveRecord::Base.update_all - 来自文档:

It sounds like you are looking for ActiveRecord::Base.update_all - from the documentation:

更新所有记录,如果它们与提供的一组条件匹配,则提供详细信息,也可以提供限制和顺序.此方法构造单个 SQL UPDATE 语句并将其直接发送到数据库.它不会实例化所涉及的模型,也不会触发 Active Record 回调或验证.

Updates all records with details given if they match a set of conditions supplied, limits and order can also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations.

Product.last_day_of_freshness.update_all(:stale => true)

实际上,由于这是 rails 2.x(您没有指定)-named_scope 链接可能不起作用,您可能需要将命名范围的条件作为第二个参数传递给 update_all,而不是将其链接到产品范围结束.

Actually, since this is rails 2.x (You didn't specify) - the named_scope chaining may not work, you might need to pass the conditions for your named scope as the second parameter to update_all instead of chaining it onto the end of the Product scope.

这篇关于在 rails 中一次更新多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆