Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 675
lost9123193 Avatar asked Nov 25 '25 02:11

lost9123193


1 Answers

Try find_or_create_by

animal = Animal.find_or_create_by(name: name, type: type)
like image 83
Mark Avatar answered Nov 27 '25 15:11

Mark