4
\$\begingroup\$

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?

asked Aug 20, 2014 at 4:40
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

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.

answered Aug 20, 2014 at 5:07
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.