This project is archived and is in readonly mode.
Add AR::Base#just_created? to differentiate records
I recently had a need to know if an record created using find_or_create was found or created. I got around it via find_or_initialize then creating a local variable for the status of new_record? then saving the record then performing my new operation based off that local variable but i couldn't help feeling that I was either missing some existing Rails functionality or that others would benefit from this functionality being added. I'm not set on the method name or anything but it indicates the intention of the code.
Comments and changes to this ticket
To clarify the benefit of this over writing out the find_or_initialize song and dance mentioned above there are two cases where having a method to check would be better.
- Where the find_or_create call is internal to a another wrapper method.
- Where you need to operate on a saved record [most likely needing the id attribute].
I'll +1 this as well. I am doing my own find_or_create'ish code in an update (trying to properly handle proper PUT semantics), and need exactly this. I thought rails had new_record_before_save?, but that appears to be part of the association internals.
I like the method name as well.
I'm not sure what the behavior of multiple saves should be:
item = Item.create item.save # should just_created? still be true here
I personally could see an argument for either, but I'd think it should be false after the 2nd save. Especially if the object changed between the saves.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>