Anybody know a Rails method that will allow me to look for an existing record or create a new one AND execute a subsequent block of code?
Example:
Model.where(parameters).first_or_create do |m|
# execute this regardless of whether record exists or not
end
Similarly, the method find_or_create_by
does not execute a block in either scenario.
I could use if-else
statements but that will duplicate my code...
I picked this up from a great screencast by ryan bates:
Model.where(parameters).first_or_create.tap do |m|
# execute this regardless of whether record exists or not
end
(where User#tap
selects the user)
I think this way looks a little cleaner, and you don't have to define another helper method as with Mischa's answer. Both work fine though.
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