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
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})
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With