Foo.where(:some_id => 1).update_all(:some_columnn => "1")
Is this the right way to update Foo? I don't want to do a find and update the object.
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.
An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).
The key thing to note is that #find returns the actual record while #where returns an ActiveRecord::Relation which basically acts like an array.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...
As of Rails 4, the conditions are no longer supplied on the update_all
method, but are instead specified on the preceding collection. For example,
# updates everything, as usual
Foo.update_all(some_column: '1')
# update only the specified rows
Foo.where(some_id: 1).update_all(some_column: '1')
Yes it is the right way, but remember, no callbacks or validations will be executed.
BTW, update_all accepts conditions also. Like this
Foo.update_all({:some_columnn => "1"}, {:some_id => 1})
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