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);
Try find_or_create_by
animal = Animal.find_or_create_by(name: name, type: type)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With