Dan Benjamin
Dan Benjamin

Reputation: 900

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?

Upvotes: 6

Views: 14665

Answers (2)

Muntasim
Muntasim

Reputation: 6786

If you dont have the object to update and you want to trigger the AR callbacks after update then this will make two sql queries but nice looking:

Model.update(id, {something: something})

If you dont bothered with the callbacks, you can use:

Model.update_all({something: something}, {id: id})

Upvotes: 4

usha
usha

Reputation: 29349

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

Upvotes: 4

Related Questions