Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update multiple columns in Ruby on Rails 3?

Just out of curiosity, is there a way to say this...

user.update_column(:field1, true)
user.update_column(:field2, true)

... in one line in Ruby on Rails?

As far as I know an update_columns method does not exist...

like image 552
Tintin81 Avatar asked Feb 14 '13 17:02

Tintin81


3 Answers

You can use update_all as follows:

User.where(:id => user.id).update_all({:field1 => true, :field2 => true})

This will generate the following update statement (mysql):

UPDATE users SET field1 = 1, field2 = 1 WHERE users.id = <whatever>

Callbacks and validations will not be run.

like image 100
Jeff Schuman Avatar answered Oct 02 '22 18:10

Jeff Schuman


Note: this is only available in ActiveRecord v4.0.2 and higher:

You can do in this way:

update_columns(field1: value, filed2: value)
like image 41
Adriano Tadao Avatar answered Oct 02 '22 17:10

Adriano Tadao


what about doing it like this:

user.attributes = attributes
user.save(validate: false)
like image 32
vitaLee Avatar answered Oct 02 '22 18:10

vitaLee