Question

I have a pretty common helper method in my application helper:

module ApplicationHelper
    def quid(num)
        number_to_currency (num / 100.0), unit: "£" 
    end 
end

But my applications keeps throwing an 'undefined method `/' for nil:NilClass' error.

If I print number_to_currency (num) it doesn't have an issue, it's only when I try to put an operator like / * - + that it gives this error.

This was working fine until today, and it's only in the product index view that I get the error.

I'm not sure what's wrong, can anyone help explain? I'm stumped!

UPDATE:

Here's the product index view code:

    <% @products.each do |product| %>

        <h3><%= product.title %></h3>
        <div id="link_text"><%= link_to "See more", product %></div>
        <%= image_tag(product.avatar.url(:medium)) %><br/>
        <%= product.description %><br />
        <%= quid product.price_in_pence %>

    <% end %>

price_in_pence is an integer, but turning 100.00 into 100 doesn't help, so I don't think that's the issue, I think it is because num is returning nil for some reason.

Was it helpful?

Solution

The error comes, because the num variable is nil in some cases. number_to_currency(nil) works, because the helper is implemented like this:

def number_to_currency(number, options = {})
  return unless number
  ...
end

source: http://apidock.com/rails/ActionView/Helpers/NumberHelper/number_to_currency

You see, a nil doesn't hurt here, because it will instantly return.

Your function, however, tries to execute nil / 100.0 first. As the error states, the / method is not defined on nil.

You probably need some special nil treatment, or hunt the cases when nil is given to your helper.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top