Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top