Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a column without loading the object in ActiveRecord

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.

like image 652
Rpj Avatar asked Oct 04 '22 12:10

Rpj


People also ask

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

What is an ActiveRecord relation object?

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).

Is ActiveRecord relation an array?

The key thing to note is that #find returns the actual record while #where returns an ActiveRecord::Relation which basically acts like an array.

What does ActiveRecord base do?

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...


2 Answers

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')
like image 198
Barry Avatar answered Oct 12 '22 11:10

Barry


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})
like image 32
Santhosh Avatar answered Oct 12 '22 11:10

Santhosh