Skip to main content
 首页 » 编程设计

ruby-on-rails之在rails中我如何委托(delegate)给一个类方法

2025年02月15日40落叶

class Task < ActiveRecord::Base 
  attr_accessible :due_date, :text 
 
  def self.this_week 
    where(:due_date => Date.today.beginning_of_week..Date.today.end_of_week) 
  end 
end 
 
class Important < ActiveRecord::Base 
  attr_accessible :email 
 
  has_one :task, :as => :taskable, :dependent => :destroy 
 
  delegate this_week, :to => :task 
end 

到目前为止,当我尝试 Important.this_week 时,这个代表没有按预期工作.我收到一条错误消息,提示没有方法 this_week为类定义...

有任何想法吗?我什至可以委托(delegate)给这样的类方法吗?我可能还有一两个扩展类(class) Task以这种方式,所以我很好奇这是如何以一种不会将一堆代码复制到每个实现类的方式工作的。

请您参考如下方法:

您正在接听 ActiveSupport delegation core extension . delegate helper 为当前类定义了一个实例方法,以便它的实例将调用委托(delegate)给该实例上的某个变量。

如果要在类级别进行委托(delegate),则需要打开单例类并在那里设置委托(delegate):

class Important < ActiveRecord::Base 
  attr_accessible :email 
 
  has_one :task, :as => :taskable, :dependent => :destroy 
 
  class << self 
    delegate :this_week, :to => :task 
  end 
end 

但这假设 Important.task是对 Task 的引用类(不是)

而不是依赖委托(delegate)助手,这只会让你的生活变得困难,我建议在这里显式代理:
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