ActiveRecord without default scope

This is a pretty hacky implementation of the feature we needed:
remove the default scope for some queries (e.g. update deleted records)

Code:

class ActiveRecord::Base
  def self.without_default_scope(&block)
    scope = scoped({})
    defaults = scope.current_scoped_methods_when_defined

    old = defaults[:find][:conditions]
    defaults[:find][:conditions] = {}

    begin
      yield(scope)
    ensure
      defaults[:find][:conditions] = old
    end
  end
end

Usage

MYModel.without_default_scope{|s| s.update_all(:deleted_at => nil)}

There is an less hacky alternative, but it did not work for us (AR 2.3.2)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s