Rails: Why is the “number_with_delimiter” method not recognized inside my model?

China☆狼群 提交于 2020-01-21 04:36:08

问题


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?


回答1:


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.




回答2:


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

For example:

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




回答3:


You should use extend:

Usage: extend ActionView::Helpers::NumberHelper

It is good for me




回答4:


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

Check the official Rails docs



来源:https://stackoverflow.com/questions/4467697/rails-why-is-the-number-with-delimiter-method-not-recognized-inside-my-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!