[ rails ] ActiveRecord find_or_initialize_by

Like find_or_create_by, but calls new instead of create.

Documentation

def find_or_initialize_by(attributes, &block)
find_by(attributes) || new(attributes, &block)
end

Example

MyModel.find_or_initialize_by(
whatever_model_attribute: whatever_model_value
)

ActiveRecord new v.s. create

new method creates an object instance

create method additionally tries to save it to the database

ref : https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_initialize_by,

https://stackoverflow.com/questions/4333163/rails-difference-between-create-and-new-methods-in-activerecord

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s