How to set a variable if a record exists

ruby, ruby-on-rails

Solution

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.

Problem

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 ```

Original source