[Rails] Re: Whats a good way to avoid nil lookup errors
So this would be the convention right? not by using rescue_from. Is
this right?
On Sep 5, 9:42 pm, Rob Biedenharn <R...@AgileConsultingLLC.com> wrote:
> On Sep 5, 2010, at 9:30 AM, Simon Macneall wrote:
>
> > On Sun, 05 Sep 2010 21:21:25 +0800, Michael Pavling
> > <pavl...@gmail.com> wrote:
>
> >> @user = User.find(1) if User.exists?(1)
>
> >> I don't like doing two lookups for one record, but it works
>
> > What about
> > @user = User.find(:first, :conditions => {:id => 1})
> > if (@user)
> > blah, blah, blah
> > end
>
> > It's longer to type, but returns nil if the user doesn't exist.
>
> Ugis almost has it. Try this
>
> @user = User.find_by_id(1)
> unless @user
> flash[:notice] = "can't find user with given id"
> redirect_to users_path
> end
>
> ActiveRecord::Base#find_by_id is a dynamic finder that will work just
> like the line Simon has above--nil if there is no record found.
>
> -Rob
>
> Rob Biedenharn
> R...@AgileConsultingLLC.com http://AgileConsultingLLC.com/
> r...@GaslightSoftware.com http://GaslightSoftware.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 rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home