In rails how can I delegate to a class method

You’re picking up the ActiveSupport delegation core extension. The delegate helper defines an instance method for the current class so that instances of it delegate calls to some variable on that instance.

If you want to delegate at the class level, you need to open up the singleton class and set up the delegation there:

class Important < ActiveRecord::Base
  attr_accessible :email

  has_one :task, :as => :taskable, :dependent => :destroy

  class << self
    delegate :this_week, :to => :task
  end
end

But this assumes that Important.task is a reference to the Task class (which it is not)

Rather than relying on the delegation helper, which is just going to make your life difficult, I’d suggest explicit proxying here:

class Important < ActiveRecord::Base
  attr_accessible :email

  has_one :task, :as => :taskable, :dependent => :destroy

  class << self
    def this_week(*args, &block)
      Task.this_week(*args, &block)
    end
  end
end

Leave a Comment