开发者

Dealing with expected nils

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 ju开发者_高级运维st 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!


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


Refactor of dcneiner's answer:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜