12

I have a simple validation:

class Product < ActiveRecord::Base
  # include ActionView::Helpers::NumberHelper
  ...
  validates_numericality_of :price, :less_than => 1000000, 
                            :message => "must be less than #{number_with_delimiter(1000000)}"                       
  ...
end

On this code, I have received the following error:

undefined method `number_with_delimiter' for #<Class:0x2665a58>

I tried to add:

include ActionView::Helpers::NumberHelper

but it didn't help.

What am I missing?

NmdMystery
  • 2,778
  • 3
  • 32
  • 60
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

5 Answers5

19

The true problem here is that you're including this module into the class, rather than extended the class with it.

The differences is an include will make the methods available on the instance, where as the extend will make them where you're trying to use them: on the class.

For instance method use

include ActionView::Helpers::NumberHelper

For class method use

extend ActionView::Helpers::NumberHelper
Ahmad Hussain
  • 2,443
  • 20
  • 27
Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • @Ryan: I understand that including inside the class is equivalent to defining my own methods in this class, right ? Does this means that I could use `self.number_with_delimiter(...)` ? When you put the `include` outside the class, are all methods inside `ActionView::Helpers::NumberHelper` becomes global ? – Misha Moroshko Dec 17 '10 at 09:01
  • @Misha: Yes they'd become global but that's generally Not A Good Idea(tm). Best thing to do in this case is to `extend` the class with the module. – Ryan Bigg Dec 17 '10 at 10:27
  • @Ryan: How do I extend the `Product` class with the `NumberHelper` module ? Isn't this what I did above ? – Misha Moroshko Dec 17 '10 at 12:42
  • @Misha: No, you're `include`'ing the module. `extend` is different. – Ryan Bigg Dec 17 '10 at 13:58
  • @Ryan: I'm confused. Including the module in model's class is exactly what I did above, and it didn't work. It worked, however, when I moved the `include` outside the class. – Misha Moroshko Dec 18 '10 at 02:04
5

Instead of extending ActionView module. You can use methods from ActiveSupport instead

For example:

ActiveSupport::NumberHelper::number_to_currency(10000.1234,{precision: 2,unit: ''})

Le Duc Duy
  • 1,881
  • 1
  • 19
  • 18
3

You should use extend:

Usage: extend ActionView::Helpers::NumberHelper

It is good for me

Tallboy
  • 12,847
  • 13
  • 82
  • 173
taivn07
  • 159
  • 1
  • 4
2

You might be missing the dependency... is the NumberHelper class accessible to your application?

Check the official Rails docs

Bnjmn
  • 1,973
  • 1
  • 20
  • 34
2

good answer, use :

ActiveSupport::NumberHelper::number_to_delimited(number, options={})

Matrix
  • 3,458
  • 6
  • 40
  • 76