HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Check if a record already exists and update if it exists

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
updatealreadyrecordexistsandcheck

Problem

I want to check if a record already exists in a database, and return 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?
  end


Or

def repeated?(unprocessed)
    occurrence = Occurrence.find_by(unprocessed: unprocessed)

    if occurrence.present?
      occurrence.touch_with_version
      true
    else          
      false
    end        
  end


Is there a better way?

Solution

When working within a Rails environment you can use try

occurrence.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.