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.
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