Rails nil errors - any way to stop them? -



Rails nil errors - any way to stop them? -

i've been learning rails past 6 months. think it's great!

but, 99% of errors app gets nil errors. i'm either trying display field nil or foreign key pointing record has been deleted.

i have type of code in many places:

<% if location.parent != nil %> <td><%= location.parent.name %></td> <% else %> <td></td> <% end %> <% if location.client_id != nil %> <td><%= location.client.client_name %></td> <% else %> <td></td> <% end %>

i wish rails show blank when field nil! or, set flash error , still show page. instead, page bombs. on heroku, "sorry, somethings wrong...."

is there way improve handle blank fields? there improve way code above? there rails setting i'm not aware of? there gem handle these type of errors?

you should place foreign key constraints , after_destroy methods on associations. stop database getting inconsistant state.

but aside refactor should checkout activesupport , various additions makes ruby. see http://guides.rubyonrails.org/active_support_core_extensions.html.

there 3 methods available on object think helpful you:

blank? - returns true if object nil, empty?, false , other conditions. see the documentation improve explanation. present? - returns true if object not nil, not empty? or true. see the documentation improve explanation. try(:foo) - attempts phone call method foo on object, returns nil if object nil. see the documentation improve explanation.

with sample code be:

<td><%= location.parent.try(:name) %></td> <td><%= location.parent.try(:client_name) %></td>

i recommend have @ why expecting object not nil. foreign key constraints in migration , after_destroy hooks associations help this.

ruby-on-rails-3

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -