why use rescue nil?

92 views
Skip to first unread message

John Merlino

unread,
Jun 19, 2012, 8:29:25 PM6/19/12
to Ruby on Rails: Talk
Hey all,

I saw this piece of code:

@user = User.find(params[:user_id]) rescue nil

why rescue with a nil here? If the user is not found, it will be nil
anyway.

Fernando Almeida

unread,
Jun 19, 2012, 8:33:12 PM6/19/12
to rubyonra...@googlegroups.com
if the record is not found the find() throws an exception.

2012/6/19 John Merlino <stoi...@aol.com>

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.




--
Fernando Almeida
www.fernandoalmeida.net

Fernando Almeida

unread,
Jun 19, 2012, 8:34:05 PM6/19/12
to rubyonra...@googlegroups.com

John Merlino

unread,
Jun 19, 2012, 8:55:58 PM6/19/12
to Ruby on Rails: Talk
ok I thought it would return nil

thanks for response

On Jun 19, 8:33 pm, Fernando Almeida <ferna...@fernandoalmeida.net>
wrote:
> if the record is not found the find() throws an exception.
>
> 2012/6/19 John Merlino <stoici...@aol.com>

Michael Pavling

unread,
Jun 20, 2012, 3:44:22 AM6/20/12
to rubyonra...@googlegroups.com
On 20 June 2012 01:55, John Merlino <stoi...@aol.com> wrote:
> ok I thought it would return nil

It would take 30seconds to try it out in a console...

Alex Mercer

unread,
Jun 20, 2012, 5:19:30 AM6/20/12
to rubyonra...@googlegroups.com
Alson you could just use where:
  @user = User.where(:id => params[:user_id]).first

Matt Jones

unread,
Jun 20, 2012, 7:56:20 AM6/20/12
to rubyonra...@googlegroups.com


On Tuesday, 19 June 2012 20:29:25 UTC-4, John Merlino wrote:
Hey all,

I saw this piece of code:

@user = User.find(params[:user_id]) rescue nil

why rescue with a nil here? 

Because the author forgot about find_by_id, which would accomplish the exact same thing (returning nil if no record was found).

--Matt Jones 

Mirri Kim

unread,
Jun 20, 2012, 1:53:50 AM6/20/12
to rubyonra...@googlegroups.com
Just a reminder: it's just specific with the find(). find_by_* will return nil unless you add a ! (e,g,, find_by_name!()) then it also returns the exception
Reply all
Reply to author
Forward
0 new messages