AnApprentice
AnApprentice

Reputation: 110950

Rails - find or create - is there a find or build?

I'm currently using:

XXX.find_or_create_by_uuid(XXXX)

Is there a way to do find or build?

Upvotes: 75

Views: 22358

Answers (3)

eeeeeean
eeeeeean

Reputation: 1834

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

Upvotes: -3

Randomtheories
Randomtheories

Reputation: 1290

Since Rails 4 this is XXX.find_or_initialize_by(uuid: XXXX)

Upvotes: 32

Dylan Markow
Dylan Markow

Reputation: 124419

Try XXX.find_or_initialize_by_uuid(XXXX)

Upvotes: 106

Related Questions