Ruby on rails 在模型类方法上运行帮助器方法
我创建了一个helper方法,我想在一个模型类方法上运行该方法,并得到一个methodnotfound错误 lib/model\u助手Ruby on rails 在模型类方法上运行帮助器方法,ruby-on-rails,ruby,activerecord,module,helper,Ruby On Rails,Ruby,Activerecord,Module,Helper,我创建了一个helper方法,我想在一个模型类方法上运行该方法,并得到一个methodnotfound错误 lib/model\u助手 module ModelHelper def method_i_want_to_use puts "I want to use this method" end end 模型/foo class Foo < ActiveRecord::Base include ModelHelper def self.bar
module ModelHelper
def method_i_want_to_use
puts "I want to use this method"
end
end
模型/foo
class Foo < ActiveRecord::Base
include ModelHelper
def self.bar
method_i_want_to_use
end
end
class Foo
此设置给了我一个无方法错误。您必须
扩展
模块,而不是包含
extend ModelHelper
include
将这些方法作为Foo
的实例方法提供。这意味着,您可以在Foo
的实例上调用我希望使用的方法method,而不是在Foo
本身上。如果要调用Foo
本身,请使用extend
module ModelHelper
def method_i_want_to_use
puts "I want to use this method"
end
end
class Foo
extend ModelHelper
def self.bar
method_i_want_to_use
end
end
Foo.bar
# >> I want to use this method
不要在模型中使用辅助对象,这不是它们的用途。请改用关注。@BroiSatse True。。而且正确。