Back to Blog

Get in Touch

with_scope is protected

By Dave Naffis August 10, 2007 in

Missing

I've seen a lot of people run into trouble using with_scope on edge. It's now a protected method Ticket: http://dev.rubyonrails.org/ticket/8524.

The solution? Don't use it or use it sparingly. They made it protected for a reason - to protect people from abusing it - but if you absolutely must have at it then you can do something like this:

 klass.send(:with_scope, :find => { :conditions => conditions }) { yield }

So say you want to scope your finders to retrieve only MyModel objects of type 'super':

def my_super_duper_scoping(klass)
  klass.send(:with_scope, :find => { :conditions => "type = 'super'" }) { yield }
end

my_super_models = my_super_duper_scoping(MyModel) do
    MyModel.find(:all)
  end

my_super_models_named_david = my_super_duper_scoping(MyModel) do
    MyModel.find(:all, :conditions => ["name = '?'", 'david')
  end

Using self.class.send is a way to get around public and private checking in ruby 1.8. Use with caution.

Medium

Dave Naffis

David is an entrepreneur and software developer with demonstrated experience in software services, product development, strategy, and operations. He is a co-founder of Intridea, an Inc 500 winning software development firm where he oversaw several successful product spinouts. Before starting Intridea, Dave ran his own Ruby on Rails consultancy and worked as a software engineer and architect at companies including AOL, Cisco, and McKinsey. He holds a masters in Systems Engineering from The University of Virginia, has contributed to a number of open-source projects, and has spoken at numerous regional and national conferences.

More posts by Dave Naffis

Dave Naffis

Four years ago, what started as a team of three people with a conviction t...

Dave Naffis

In this new blog series, Why Your Company Needs a Rails Development S...

Dave Naffis