#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 10 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. uggs short 5825 tomato red sale Jan 19, 2010 at 09:26

thanks for the information.


6. GHD IV Styler Black Jan 19, 2010 at 09:27

i like the site.


7. Lerusya Feb 04, 2010 at 23:58

I think i have same problem too, but i see there is no admin or support to reply our comment :)


8. Kristinka Feb 10, 2010 at 12:48

A very good article, I will always come in.


9. Leontinka Feb 11, 2010 at 14:10

Such a good article, caught my sympathy!


10. Vitunya Feb 26, 2010 at 16:02

Of course it is good article!

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
Give Back to Open Source