解决方法
我这样做:
1)向delayed_jobs表添加两个新列
分贝/迁移/ 201109
Order.jobs # lists all the running jobs for Order class order1.jobs # lists all the running jobs for Order object order1
963_add_owner_to_delayed_jobs.rb
class AddOwnerToDelayedJobs < ActiveRecord::Migration def self.up add_column :delayed_jobs,:owner_type,:string add_column :delayed_jobs,:owner_id,:integer add_index :delayed_jobs,[:owner_type,:owner_id] end def self.down remove_column :delayed_jobs,:owner_type remove_column :delayed_jobs,:owner_id end end
2)向Delayed :: Job模型添加多态关联
配置/初始化/ delayed_job.rb
class Delayed::Job < ActiveRecord::Base belongs_to :owner,:polymorphic => true attr_accessible :owner,:owner_id end
3)猴子补丁ActiveRecord :: Base包含作业关联
配置/初始化/ active_record.rb
class ActiveRecord::Base has_many :jobs,:class_name => "Delayed::Job",:as => :owner def send_at(time,method,*args) Delayed::Job.transaction do job = Delayed::Job.enqueue(Delayed::PerformableMethod.new(self,method.to_sym,args),10,time) job.owner = self job.save end end def self.jobs # to address the STI scenario we use base_class.name. # downside: you have to write extra code to filter STI class specific instance. Delayed::Job.find_all_by_owner_type(self.base_class.name) end end
4)触发工作
class Order < ActiveRecord::Base after_create :set_reminders def set_reminders send_at(2.days.from_now,:send_email_reminder) end def send_email_reminder end # setting owner for handle_asynchronously notation. def foo end handle_asynchronously :foo,:owner => Proc.new { |o| o } end
5)检查工作
Order.jobs # lists all the running jobs for Order class order1.jobs # lists all the running jobs for Order object order1