質問

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