In Rails, execute block for both conditions: first_or_create

安稳与你 提交于 2019-12-22 08:15:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!