The project currently I’m working has the following code in the view:
<%= product.provider.name %>
The above code is get the ‘provider’ for a product and display his/her name. But my question was sometimes this code fails when’provider’ gets nil. (I know it’s little unusual but since I’m working with a legacy db this happens)
So to check the nil validation I have written the following code (in my ApplicationHelper)
def t(obj, attr)
obj.nil? ? "" : obj.send(attr.to_sym)
end
Now what I do is something like this:
<%= t(product.provider, "name") %>
Even though this works, I ran in to another problem, I found this code:
<%= product.provider.provider_type.title %>
The problem here is, in the above code either ‘provider’ or ‘provider_type’ can be nil.
What I’m looking at is an exception handling mechanism to handle any number of nested relationship.
Or is this a completely wrong path to handle nil values in nested relations? I’m running on Rails 2.3.8.
You can rescue all exceptions: