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…
According to the API, the block in your example will only execute if the record does not exist. But you don’t need a block, nor an if-else:
Be aware that some validations on the object may have failed and therefore
mmay not have persisted to the database yet.