patternrubyrailsMinor
Check if a record already exists and update if it exists
Viewed 0 times
updatealreadyrecordexistsandcheck
Problem
I want to check if a record already exists in a database, and return
If it exists, I want to update the
Which is better?
Or
Is there a better way?
true or false.If it exists, I want to update the
update_at datetime field. The method touch_with_version from the paper_trail gem will do it.Which is better?
def repeated?(unprocessed)
occurrence = Occurrence.find_by(unprocessed: unprocessed)
occurrence.touch_with_version if occurrence.present?
occurrence.present?
endOr
def repeated?(unprocessed)
occurrence = Occurrence.find_by(unprocessed: unprocessed)
if occurrence.present?
occurrence.touch_with_version
true
else
false
end
endIs there a better way?
Solution
When working within a Rails environment you can use
Ruby also provides
You could even dig into the libraries to see that
If you're happy returning
Very nice but also more fragile if either of those libraries decide to change their return values in a future release.
tryoccurrence.try(:touch_with_version)
occurrence.present?Ruby also provides
tap so you could also write:occurrence.tap({|o| o.try(:touch_with_version)}).present?You could even dig into the libraries to see that
touch_with_version returns the result of ActiveRecord's save! which in turn returns the result of create_or_update which returns a boolean and so you can write:occurrence.try(:touch_with_version).present?If you're happy returning
true, false, or nil you could shorten it to:occurrence.try(:touch_with_version)Very nice but also more fragile if either of those libraries decide to change their return values in a future release.
Code Snippets
occurrence.try(:touch_with_version)
occurrence.present?occurrence.tap({|o| o.try(:touch_with_version)}).present?occurrence.try(:touch_with_version).present?occurrence.try(:touch_with_version)Context
StackExchange Code Review Q#60547, answer score: 5
Revisions (0)
No revisions yet.