Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update a record without worrying about primary key

In ActiveRecord how can we update a record without worrying/knowing primary key.

If I do

Address.update(15, :user_name => 'Samuel')

it corresponds to

UPDATE addresses set user_name = 'Samuel' where id = 15

but what if i want to do:

UPDATE addresses set user_name = 'Samuel' where cid = 15

what will be the ActiveRecord equivalent of that??

I tried:

Address.update({:cid => 15}, :user_name => 'Samuel')

but that does not work.

like image 418
railsnew Avatar asked Apr 26 '10 02:04

railsnew


1 Answers

Use the update_all class method:

Address.where(:cid => 15).update_all(user_name : 'Samuel')

http://apidock.com/rails/ActiveRecord/Relation/update_all

like image 66
typeoneerror Avatar answered Nov 22 '22 17:11

typeoneerror