R – Dealing with expected nils

nullruby-on-rails

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!

Best Answer

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? %>
Related Topic