I have a controller promos. When the edit action is called the following error is given - Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id For simplicity the controller and view looks like this: promos_controller.rb -------------------------------- def edit @promo = Promo.find(params[:id]) end ------------------------------ edit.html.erb ------------------------------- <%= @promo.id %> ---------------------------- However when I change the instance variable to say @home, or anything else the view correctly displays the results. Could anyone explain why it wouldn''t work for @promo?
Rick DeNatale
2009-Jul-02 12:28 UTC
Re: Why!? A strange instance variable in action and view
On Thu, Jul 2, 2009 at 1:47 AM, Dandan<icelavagles-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> > I have a controller promos. When the edit action is called the > following error is given - > Called id for nil, which would mistakenly be 4 -- if you really wanted > the id of nil, use object_id > > For simplicity the controller and view looks like this: > > promos_controller.rb > -------------------------------- > def edit > @promo = Promo.find(params[:id]) > end > ------------------------------ > edit.html.erb > ------------------------------- > <%= @promo.id %> > ---------------------------- > > However when I change the instance variable to say @home, or anything > else the view correctly displays the results. > > Could anyone explain why it wouldn''t work for @promo?It''s not the instance variable name, it''s that that instance variable has a nil value. What was the id parameter in the request? I suspect that the find failed to find a record with that id, which would cause it to return nil. Your controller should be doing something like: def edit unless(@promo = Promo.find(params[:id])) # There was no promo with that id # Perform some appropriate error action # Which might involve setting the flash with an error msg # and redirecting somewhere end end -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale
Jeffrey L. Taylor
2009-Jul-02 20:41 UTC
Re: Why!? A strange instance variable in action and view
Quoting Dandan <icelavagles-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>: [snip]> promos_controller.rb > -------------------------------- > def edit > @promo = Promo.find(params[:id]) > end > ------------------------------ > edit.html.erb > ------------------------------- > <%= @promo.id %> > ----------------------------I find that model.id is troublesome. model[:id] works quite reliably for me. HTH, Jeffrey