Sep 02 2007
When a database field in a table is NULL and this field is then used in a view a nil object exception will be raised. So for example if I had the following code to display the name of the user in my view and the login field was NULL an error would be generated as login object would be nil.
Signed in as <%= current_user.login %>
To overcome this you would need to use something like the code below:
Signed in as <%= current_user.login unless current_user.login.blank? %>
Which if you have many field to deal with becomes a major pain. As I was reading about this I realised that nil in Ruby is an actual object that has methods including to_s which will return an empty string when called. So instead I can do the following:
Signed in as <%= current_user.login.to_s %>
When the login field is NULL a nil object will be returned and the to_s message sent to this object which in turn will return an empty string, no error messages will be generted and everything works nicely.