Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 981
jcollum Avatar asked Oct 30 '25 23:10

jcollum


2 Answers

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

like image 103
RameshVel Avatar answered Nov 02 '25 23:11

RameshVel


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.

like image 29
flh Avatar answered Nov 02 '25 22:11

flh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!