#5
Mar 14, 2007

Using with_scope

Learn how to use with_scope - a very powerful method which will allow your custom find methods to accept any find options. Just like magic!
Download (5.9 MB, 2:50)
alternative download for iPod & Apple TV (3.9 MB, 2:50)
# models/task.rb
def self.find_incomplete(options = {})
  with_scope :find => options do
    find_all_by_complete(false, :order => 'created_at DESC')
  end
end

RSS Feed for Episode Comments 5 comments

1. bradc Jun 27, 2007 at 12:37

If I specify an :order option when calling find_incomplete, will with_scope override the one that's already defined by default?


2. Ryan Bates Jun 27, 2007 at 15:57

@bradc, good question. There's no way to override the default :order by passing the options. To change this behavior you need to reverse it so the :order statement is in with_scope and the options are passed directly to the find method.


3. Eric Anderson Oct 16, 2007 at 20:00

I typically reverse the custom find methods so that I also have the option of specifying the type of find I want to do (i.e. :first, :all, array of ids, etc.). So my code would look something like:

<code>
<pre>
def self.find_incomplete(*args, &blk)
  with_scope :find => {:conditions => ['complete = ?', false],
    :order => 'created_at DESC'} do
    find *args, &blk
  end
end
</pre>
</code>

The &blk is not really necessary but if helps future-proof the interface.


4. Evgeni Belin Jan 08, 2008 at 14:15

I was having problems using will_paginate with scope_out. Another plugin "has_finder" seems to provide similar functionality only plays nicely with pagination:

http://zargony.com/2007/10/20/paginating-special-queries-with-hasfinder-and-will_paginate/


5. kino May 23, 2008 at 01:54

As is evident upon close examination, the transcendental unity of apperception is the mere result of the power of space, a blind but indispensable function of the soul.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player