#5
Mar 14
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!
# models/task.rb def self.find_incomplete(options = {}) with_scope :find => options do find_all_by_complete(false, :order => 'created_at DESC') end end




If I specify an :order option when calling find_incomplete, will with_scope override the one that's already defined by default?
@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.
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.
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/