覆盖rails 3中的范围

时间:2010-10-24 18:00:17

标签: ruby-on-rails activerecord named-scope

我想覆盖现有范围以向其添加额外条件。我已经尝试使用alias_method尝试这样做了。不幸的是,这种方法不适用于范围,我得到一个未定义的方法错误。我如何使用范围进行操作?

module Delayed
  module Backend
    module ActiveRecord
      class Job < ::ActiveRecord::Base
        belongs_to :queue

        scope :in_unlocked_queue, lambda {
          joins(:queue) & Queue.unlocked
        }

        alias_method :orig_ready_to_run, :ready_to_run
        scope :ready_to_run, lambda {|worker_name, max_run_time|
          orig_ready_to_run(worker_name, max_run_time).in_unlocked_queue
        }
      end
    end
  end
end

1 个答案:

答案 0 :(得分:2)

好的,这是一个答案,不确定它是否最干净但是有效

require 'delayed_job'

module Delayed
  module Backend
    module ActiveRecord
      class Job < ::ActiveRecord::Base
        belongs_to :queue

        scope :in_unlocked_queue, lambda {
          joins(:queue) & Queue.unlocked
        }

        scope :orig_ready_to_run, scopes[:ready_to_run]
        scope :ready_to_run, lambda {|worker_name, max_run_time|
          orig_ready_to_run(worker_name, max_run_time).in_unlocked_queue
        }
      end
    end
  end
end