Rails - find or create - is there a find or build?
I'm currently using:
XXX.find_or_create_by_uuid(XXXX)
Is there a w开发者_C百科ay to do find or build?
Try XXX.find_or_initialize_by_uuid(XXXX)
Since Rails 4 this is XXX.find_or_initialize_by(uuid: XXXX)
In case you want to make your own (Rails 5):
class ApplicationRecord < ActiveRecord::Base
def self.find_or_build_by hash
result = all.where(hash)
result.present? ? result : none.build(hash)
end
end
精彩评论