3

What is the best way to check if a record exists before 'creating' the object?

@tag = Tag.find_by_name(tag)
if @tag
 do_something
else
 do_something_else
end

Can you do:

if @tag = Tag.find_by_name(tag)
 do_something
else
 do_something_else
end
1
  • I like first approach.. Commented Jan 27, 2014 at 14:29

1 Answer 1

10

Both versions are perfectly fine. It's very common to use the latter, because it's more concise. However, for readability, you may want to use

if (@tag = Tag.find_by_name(tag))

This is not necessary, but it makes it more explicit that you are doing an assignment and not a comparison.

if @tag == Tag.find_by_name(tag)

Wrapping it into parenthesis is more explicit. It says, assign, then evaluate the result.

Furthermore, if you don't actually need the tag object itself, and you just care for the existence, you may want to use exist?

if Tag.exists?(name: tag)

This is faster, because it uses a SELECT COUNT SQL query and not a full SELECT. It basically doesn't instantiate the record.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 Assigning in a conditional test is a maintenance bug in waiting; People do it in C and Perl, but unless it's well commented, someone following along might not understand that it's SUPPOSED to be an assignment instead of a comparison. It's better to assign in a previous step, then compare, which makes it a lot more obvious what the intention was.
Thanks Simon. Tag.exists?(name: tag) worked for me and Tag.where(name: tag).exist? did not. Any idea why the difference in syntax?
The syntax may have changed, I should look at the API.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.