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?

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

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


Need Your Help

Override CSS values for slider background

html css overriding

I am using a java slider. DEMO The slider uses one background for all the slides (bg-sequence.jpg). I would like each slide to have its own background. How would I achieve this? Here is the CSS and...