如何验证 update_all 是否在 Rails 中实际更新 [英] How to verify if update_all was actually updated in Rails

查看:34
本文介绍了如何验证 update_all 是否在 Rails 中实际更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这个代码

def create
  @upgrades = User.update_all(["role = ?","upgraded"], :id => params[:upgrade])
  redirect_to admin_upgrades_path, :notice => "Successfully upgraded user."    
end

如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息?

How can I actually verify in that action if they were saved or not to redirect to appropriate page and message?

推荐答案

在 Rails3 中,update_all 不返回任何有意义的信息,除了更新的记录数(这可能取决于您的 DBMS 是否返回该信息).

In Rails3, update_all does not return any meaningful information except for the number of records that were updated (this may depend on if your DBMS returns that information).

http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000343

它不会实例化任何对象,您可以通过查看日志来验证这一点.

It does NOT instantiate any objects, you can verify this by looking at the log.

如果我的数据库中的用户 ID 为 4 和 5(并且没有其他用户 ID),那么我得到的是:

If I have user ID of 4 and 5 in my database (and none else), here's what I get:

irb(main):007:0> u = User.update_all( "id = id", :id => 5 ) 
=> 1
irb(main):008:0> u = User.update_all( "id = id", :id => 55 )
=> 0
irb(main):009:0> u = User.update_all( "id = id", :id => [4,5] )
=> 2
irb(main):010:0> u = User.update_all( "id = id", :id => [4,53] )
=> 1
irb(main):011:0> u.class
=> Fixnum

如果你想得到修改过的记录,你必须使用update",传入一个ID值列表,然后你就会收到实例化的对象.

If you want to get the records that were modified, you have to use "update", pass in a list of ID values, and then you will receive the instantiated objects.

请注意,如果您有很多 ID,您很容易通过实例化过多的对象来淹没服务器的内存.

Note that if you have a LOT of IDs you can easily overwhelm your server's memory by instantiating too many objects.

我能想到的另一种方法是首先查询将要升级的对象(使用对象分组并仅从表中选择您需要显示的属性,从而节省内存),生成您的报告,然后运行 ​​Update_All 查询...

The other way I could think of, would be to first do a query of the objects that WILL be upgraded (use object groupings and only select the attributes from the table that you need to display, thus saving memory), generate your report, then run the Update_All query...

这篇关于如何验证 update_all 是否在 Rails 中实际更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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