我收到了:undefined method 'important_method' for #<Class:0xbee7b80>
我致电:User.some_class_method
使用:
# models/user.rb
class User < ActiveRecord::Base
include ApplicationHelper
def self.some_class_method
important_method()
end
end
# helpers/application_helper.rb
module ApplicationHelper
def important_method()
[...]
end
end
我做错了什么?我该如何避免这个问题?
答案 0 :(得分:1)
include
通常用于在实例级别包含代码,其中extend
用于类级别。在这种情况下,您需要查看User
extend
ApplicationHelper
。我没有测试过这个,但可能就这么简单。
RailsTips在include
与extend
之间a great write-up - 我强烈推荐它。
答案 1 :(得分:0)
这不是DRY,但它有效 - 将application_helper.rb更改为:
# helpers/application_helper.rb
module ApplicationHelper
# define it and make it available as class method
extend ActiveSupport::Concern
module ClassMethods
def important_method()
[...]
end
end
# define it and make it available as intended originally (i.e. in views)
def important_method()
[...]
end
end