Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update if exists, else do nothing?

I'm trying to update a value of a model if and only if the model exists. If it doesn't, I do nothing. Searching only seems to return update or create questions/answers, but I do not want to create.

I know I can do it with a simple:

found = Model.find_by_id(id)
if found
  update stuff
end

However, I feel like there is a way to do this in one call, without assigning any temporary local values or doing an if.

How would I write a rails call to update a record without noisy errors if it doesnt exist?

Latest Rails 3.x

like image 543
Mike Manfrin Avatar asked Mar 20 '13 21:03

Mike Manfrin


2 Answers

You can use try method of Rails before calling update_attributes on result of find_by_id or where.

try will return nil silently without raising exception if the record does not exist. If the record exists, it will update it.

found = Model.find_by_id(id).try(:update_attributes, {key: value})
like image 77
Prathamesh Sonpatki Avatar answered Oct 05 '22 11:10

Prathamesh Sonpatki


You can use first_or_initialize combined with new_record? as following:

client = Client.where(first_name: 'Nick').first_or_initialize(locked: false)
client.save unless client.new_record?
like image 39
sailor Avatar answered Oct 05 '22 12:10

sailor