User.where(id: id).first_or_create! do |user|
user.assign_attributes(attributes)
end
User.find_or_create_by!(id: id) do |user|
user.assign_attributes(attributes)
end
User.where(id: id).first_or_initialize do |user|
user.assign_attributes(attributes)
user.save!
end
User.find_or_initialize_by(id: id) do |user|
user.assign_attributes(attributes)
user.save!
end
Passed attributes are only assigned if the object is newly created
Initial notes:
Keep in mind caveats of
first_or_create
,find_or_create_by
,first_or_initialize
,find_or_initialize_by
andupsert
where
andfirst_or_*
can be combined to be the same asfind_or_*_by
The body only runs if the object is newly created
Passed
attributes
are only assigned if the object is newly createdfind_or_create_by(nil)
will get the first entity while find_or_create_by(id: nil) will create a new oneValid but broken?