0

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!

Community
  • 1
  • 1
JZ.
  • 21,147
  • 32
  • 115
  • 192

2 Answers2

3

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
  • 65,509
  • 13
  • 109
  • 118
1

Refactor of dcneiner's answer:

<%=h [@inventory.origin.code] if @inventory.origin %>
Steve Graham
  • 3,001
  • 1
  • 22
  • 26