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

Ruby on-Rails

Ruby on-Rails Problem Overview


I'm currently using:

XXX.find_or_create_by_uuid(XXXX)

Is there a way to do find or build?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try XXX.find_or_initialize_by_uuid(XXXX)

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnApprenticeView Question on Stackoverflow
Solution 1 - Ruby on-RailsDylan MarkowView Answer on Stackoverflow
Solution 2 - Ruby on-RailsRandomtheoriesView Answer on Stackoverflow
Solution 3 - Ruby on-RailseeeeeeanView Answer on Stackoverflow