views:

66

answers:

2

I expect to see a nil returned with the following embedded Ruby:

<%=h [@inventory.origin.code] %>

it returns a "NoMethodError nil object". However when an object is in fact present, it functions just fine (as expected).

Therefore I created this test (following this advice):

<b>origin_id:</b>
  <% if (@inventory.origin.code.nil? or @inventory.origin.code == 0)  %>
  <%=h [@inventory.origin] %>
  <% else %>
  <%=h @inventory.origin.code %>
  <% end %>

unexpectedly rails returns NoMethodError "You have a nil object when you didn't expect it!"

Do you have any suggestions in dealing with this situation? Thanks!

+2  A: 

You are adding the .nil? check too late. I am assuming it is origin that is nil, not code or you wouldn't be getting that error. Use this instead:

<%=h [@inventory.origin.code] unless @inventory.origin.nil? %>
Doug Neiner
It works! Thank you
JZ
even tidier would be using if @inventory.origin
Omar Qureshi
A: 

Refactor of dcneiner's answer:

<%=h [@inventory.origin.code] if @inventory.origin %>
Steve Graham