Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record - Find and Update (only if object exists)

I have an id of a record that may or may not exist in the database.

What i want to do is update an attribute of the record in the database only if it exists, otherwise ignore it.

Now i know i can do something like:

model = Model.find_by_id(id)
if model
     model.update_attribute(something: something)
end

But i was wondering if there's something nicer that doesn't involve 2 queries?

like image 536
Dan Benjamin Avatar asked Oct 01 '22 21:10

Dan Benjamin


1 Answers

Model.update_all({:something => 'something'}, {:id => id})

For eg:

User.update_all({:first_name => 's'}, {:id => 1000})

will produce the query

UPDATE "users" SET "first_name" = 's' WHERE "users"."id" = 1000
like image 109
usha Avatar answered Oct 13 '22 12:10

usha