Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #3878 (closed enhancement: duplicate)

Opened 3 years ago

Last modified 3 years ago

[PATCH] find_or_new

Reported by: joey__ Assigned to: David
Priority: normal Milestone:
Component: ActiveRecord Version: 1.0.0
Severity: normal Keywords: risky
Cc:

Description

This diff adds the method: find_or_new_by* to ActiveRecord. This is self explanatory, if the object is found it is returned, if not a new instance of the object is returned but not saved.

Attachments

added_find_or_new.diff (3.6 kB) - added by joey__ on 02/18/06 13:55:02.
added_find_or_new.2.diff (3.0 kB) - added by anonymous on 02/18/06 13:58:05.

Change History

02/18/06 13:55:02 changed by joey__

  • attachment added_find_or_new.diff added.

02/18/06 13:58:05 changed by anonymous

  • attachment added_find_or_new.2.diff added.

02/18/06 13:59:06 changed by joey__

The first diff included changes to the connection settings, could this diff be deleted.

Thanks, sorry for the mishap.

02/18/06 23:04:19 changed by david

Could you show us a few snippets of application code where this is needed over find_or_create? I'd love to see when this is applicable.

02/19/06 00:43:36 changed by david

  • keywords set to risky.

02/19/06 01:12:53 changed by joey__

def create

@subscriber = Subscriber.find_or_new_by_email(params[:subscriber][:email]) if @subscriber.id #already signed up, as it has an id

render :partial => 'already'

elsif @subscriber.save

render :partial => 'success'

else

render :partial => 'form'

end

end

03/18/06 21:20:03 changed by Caio Chassot <caio@v2studio.com>

For what it's worth, I have implemented a find_or_new in my rails extensions long ago, and occasionally use it.

I think it's good over find_or_create in cases when you just need a temp object with empty/default values, that wouldn't even pass validation if tried to save.

05/08/06 02:11:52 changed by jd@wuputah.com

I went looking for this functionality last week when I wanted to use find_or_create, but then modify the resulting object and save it without doing two queries (an INSERT then an UPDATE). Right now, my options are use find_or_create and be happy with two save() calls (one from create, one from my code), or use find() and an if clause. In addition, like Caio said, it would not be difficult to make the object fail validation.

07/08/06 01:39:47 changed by bitsweat

  • status changed from new to closed.
  • resolution set to duplicate.

find_or_initialize_by_