Search code examples
ruby-on-railsrubyternary

Simply if statement to a Tenerary in Ruby


I'm new to Rails and was wondering about the following:

Is there a way to simplify this further?

  animal = Animal.find_by(name:name, type:type)
  if !animal
    animal = Animal.create(name:name, type:type)

I was thinking of using a ternary expression but i'm wondering how I would write that without repeating code or if this is the correct way of doing it.

animal = Animal.find_by(name:name, type:type) ? Animal.find_by(name:name, type:type) :  Animal.create(name:name, type:type);

Solution

  • Try find_or_create_by

    animal = Animal.find_or_create_by(name: name, type: type)