Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, execute block for both conditions: first_or_create

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...

like image 827
John Bullhuo Avatar asked Nov 27 '22 14:11

John Bullhuo


1 Answers

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.

like image 56
Eric Avatar answered Feb 07 '23 01:02

Eric