문제

I'm getting: undefined method 'important_method' for #<Class:0xbee7b80>

when I call: User.some_class_method

with:

# 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

What am I doing wrong? How can I avoid this problem?

도움이 되었습니까?

해결책

include is generally used to include code at the instance level, where extend is for the class level. In this case, you'll want to look to have User extend ApplicationHelper. I haven't tested this, but it might be that simple.

RailsTips has a great write-up on include vs. extend - I highly recommend it.

다른 팁

It's not DRY, but it works - change application_helper.rb to:

# 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top