Reputation: 11030
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);
Upvotes: 2
Views: 155
Reputation: 22225
Just one more variation:
animal = Animal.find_by(name:name, type:type) || Animal.create(name:name, type:type)
Upvotes: 0
Reputation: 21110
In your specific scenario the answer of Mark is the better answer. However I'd like to offer a clean solution of what you currently have.
Ruby allows an inline modifier-if/unless statement. This would look like this:
animal = Animal.find_by(name: name, type: type)
animal = Animal.create(name: name, type: type) unless animal
You could also make use of the ||=
operator here (which has my preference). This operator only assigns the right had value to the variable if the variable currently holds a falsy value (nil
or false
).
animal = Animal.find_by(name: name, type: type)
animal ||= Animal.create(name: name, type: type)
# or if you prefer the longer one-liner
animal = Animal.find_by(name: name, type: type) || Animal.create(name: name, type: type)
Upvotes: 1