Rails: TypeError: nil can't be coerced into Float

When working on Ruby on Rails website some of the common errors that you need to check for is nil objects when something else was expected. For instance, suppose one of your ActiveRecord models has a price field. Further suppose that the user left this field blank instead of entering 0.0 as the price.

This computation will fail:

{% codeblock lang:ruby %} quantity = 3 # … amount_to_charge = price_field * quantity {% endcodeblock %}

It fails with a “TypeError: nil can’t be coerced into Float” exception. Your user will be shown the dreaded red “We’re sorry, but something went wrong” page.

{% img center /images/posts/2012-01-14/Rails_Default_500_Error_Page.png ‘Rails Default 500 Error Page’ %}

A few observations:

In the current example, it is reasonable to treat nil as a 0.0. The following will do that:

{% codeblock lang:ruby %} quantity = 3 # … amount_to_charge = price_field.to_f * quantity {% endcodeblock %}

The same will work with integers using to_i. Instances when *nil *can reasonably considered 0 is only something that you, as the programmer can decide. In most cases it would be better to include good validations and default values in all of your models to avoid this situation altogether.

I hope this helps!

{% render_partial _includes/callouts/_web_topics_post.md %}