Forum: Ruby-Forum.com nil objects

322c3dc73326a2ab705ceb090a557fe3?d=identicon&s=25 Alex Gregianin (Guest)
on 2007-02-06 17:32
Hello ruby People!

  I'm learning ruby right now,and i got a easy question for you guys!
whenever i have a model with nil objects,when i try to actually see the
record I get the error

"You have a nil object when you didn't expect it!"

I knwo what this error means and i know why it's happenning in my
case,but my question is:

      what should i do to make rails show nil objects as blank
fields?like I'm try ing to add a new user to my system and there's 4
fields: id,username,password,description.....

let's say i did fill 2 of them(id is auto increment),and left the last
one blank....now i wanna show my record into my view,but I'm sure i will
get this error.....

You have a nil object when you didn't expect it!

     i know how to work around this also...i did something like this :
unless @model.name.nil?
   @model.name
end

but if have to do this for EVERY field into my view,i pretty much feel
like rails isn't being as much productivity as it's supposed to be...

i'm sorry for my english and of course if i'm saying something stupid
please correct me guys! thankz man!
14b5b331727b49897a14e8c651bccbcf?d=identicon&s=25 Anonymous (Guest)
on 2007-02-25 11:44
Alex Gregianin wrote:
> Hello ruby People!
>
>   I'm learning ruby right now,and i got a easy question for you guys!
> whenever i have a model with nil objects,when i try to actually see the
> record I get the error
>
> "You have a nil object when you didn't expect it!"
>

I was searching for this exact same thing, too bad no one had responded
to you yet.

One solution would be to extend the NilClass to handle missing methods
so it would behave
like /dev/null, always returning nil instead of some runtime error.
Example nil.nonexistentmethod => nil

I'd like to know what others think about this.
Fa06489a97b0efe3c3b7d249982878d3?d=identicon&s=25 David Hughes (divotdave)
on 2007-09-17 19:33
Anonymous wrote:
> Alex Gregianin wrote:
>
> I'd like to know what others think about this.

For what it's worth at this point:

<% @users.each do |u| %>
  <%= u.name rescue nil %>
<% end %>

will produce an empty space in your view where the data would go if
there is no value in that record. So unless you don't want a record to
show up at all is missing fields, you don't need the extra helper
methods...

Cheers,
divotdave
58fcb2f9e4371143e1965eac84505ee5?d=identicon&s=25 Toby Rodwell (tobyr)
on 2007-10-04 14:10
David Hughes wrote:
...
>   <%= u.name rescue nil %>
...
Neat trick - thanks very much!
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.