Given this code
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?
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.
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
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.
Note that if you have a LOT of IDs you can easily overwhelm your server's memory by instantiating too many objects.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With