Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
AnApprentice Avatar asked Jan 30 '11 17:01

AnApprentice


People also ask

What's the purpose of Active Record?

Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

What is find_ or_ create_ by Rails?

find_or_create_by is a common method used in Rails to find records based on one or many attributes that are input or create a record if it can't find it.

What is Active Record in Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is the difference between build and new in Rails?

build ... produces an object with all nil values EXCEPT for list_id. Item. new creates a new item object, with all nil values.


2 Answers

Try XXX.find_or_initialize_by_uuid(XXXX)

like image 183
Dylan Markow Avatar answered Oct 12 '22 21:10

Dylan Markow


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

like image 32
Randomtheories Avatar answered Oct 12 '22 21:10

Randomtheories