问题
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...
回答1:
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:
m = Model.where(parameters).first_or_create
m.some_method # executes regardless of whether record exists or not
Be aware that some validations on the object may have failed and therefore m
may not have persisted to the database yet.
回答2:
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.
来源:https://stackoverflow.com/questions/12255125/in-rails-execute-block-for-both-conditions-first-or-create