Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first_or_create: determining which is called

I call first_or_create like so:

collection = Collection.first_or_create(:title => title)

Is there a way to determine if the result is an existing entry or a freshly created one? So far the best solution I've come up with is to use first_or_initialize:

collection = Collection.first_or_initialize(:title => title)
if collection.id.nil?
  <process>
  collection.save
end

But this feels a bit hacky. Is there a way to get this information directly from first_or_create?

like image 699
nullnullnull Avatar asked Jan 24 '13 21:01

nullnullnull


2 Answers

first_or_create takes a block that'll only be executed if a new record is created, you can set some flag inside that block to indicate it's a new record, for example

MyObject.where(attr: "value").first_or_create do |obj|
  @my_object_created = true
end
like image 53
bigsolom Avatar answered Nov 15 '22 09:11

bigsolom


As far as I know you can't know. Two options are to check the created_at time (unreliable), or instead use first_or_initialize, then check to see if new_record? is true, and if so, do your other operations and then call save!. This may be the best approach for you anyway, since you may very well not want to finalize the save until the other relations are saved, and you probably want to do all of that in the same database transaction.

like image 36
Jim Stewart Avatar answered Nov 15 '22 11:11

Jim Stewart