Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Add AR::Base#just_created? to differentiate records

#2089

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.

Reported by RSL · February 26th, 2009 @ 10:58 PM

State: wontfix
Milestone: 2.x
Assigned to: Pratik Pratik
Importance: none

Activity

  1. RSL
    RSL
    • Title changed from Add AR::Base#just_created? to differenciate records to Add AR::Base#just_created? to differentiate records

    February 26th, 2009 @ 11:03 PM

  2. RSL
    RSL

    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.

    1. Where the find_or_create call is internal to a another wrapper method.
    2. Where you need to operate on a saved record [most likely needing the id attribute].

    February 26th, 2009 @ 11:26 PM

  3. Jaime Bellmyer
    Jaime Bellmyer
    1. It includes/passes tests, and works as advertised, and seems to stick with rails conventions. At first I didn't see the usefulness, but I have to admit after trying it out, I can see how it would be helpful. I like it!

    February 27th, 2009 @ 06:10 AM

  4. Jaime Bellmyer
    Jaime Bellmyer

    Sorry, my post above started with "+1", but formatting seems to have mangled it. +1

    February 27th, 2009 @ 06:12 AM

  5. Pratik
    Pratik
    • Assigned user set to Pratik
    • State changed from new to wontfix

    just_created? should return false for new records. Also, let's wait till someone else wants the same feature, then I'll push it.

    Thanks.

    March 9th, 2009 @ 02:42 PM

  6. RSL
  7. Richie Vos
    Richie Vos

    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.

    December 16th, 2009 @ 05:19 AM