jcollum
jcollum

Reputation: 46613

is there a way to tell if a record is new after it's been created with find_or_create_by

I'm using this code:

item = Item.find_or_create_by(:name => title.strip)
if item.changed?
   results.newItemsCount += 1
end

I want to get the count of newly created records for logging. I was hoping that the .changed property would be true for items that are newly created but it looks like it isn't. The next part of the code may modify the item even if it isn't new, so I really need to know right here if the item is new.

Is there a way to tell if the record is new or not? Didn't see anything like that in the docs. You'd think that just setting the title (in the constructor) would qualify as changed but it seems like that doesn't happen.

Upvotes: 4

Views: 1906

Answers (2)

flh
flh

Reputation: 41

Maybe it is too late, but it is possible. You can pass a block like this:

item = Item.find_or_create_by(:name => title.strip) do |_i|
  puts "Called only for newly created records"
end

Hope it will help somebody.

Upvotes: 1

RameshVel
RameshVel

Reputation: 65887

I don't think its possible to find whether the call was find or create using changed? or persisted? methods.

Instead you can do this by find_or_initialize_by. Here you can check persisted? value to determine the item is new or not. if its false then you know that its a new document.

item = Item.find_or_initialize_by(:name => title.strip)
unless item.persisted?
   item.save 
   results.newItemsCount += 1
end

Other way is you can use after_create callback. if its a new item this callback will be triggered. And you can do your operation here.

Hope it helps

Upvotes: 7

Related Questions