How to properly override ActiveRecord::Base.find

Hi,

I want the find(:all) method to only return published Comments.

This works:

Override find method to only return published comments

def self.find(*args)
options = args.extract_options!
validate_find_options(options)
set_readonly_option!(options)

case args.first
when :first then find_initial(options)
when :last  then find_last(options)
when :all   then options[:conditions] = { :published => true };

find_every(options)
else find_from_ids(args, options)
end
end

But is not very DRY since I pasted the code from active_record/base.rb.

Any improvements on this?

CmdJohnson

Commander J. wrote:

I want the find(:all) method to only return published Comments.

Use a named_scope. It’s too easy like that.


Phlip
http://flea.sourceforge.net/resume.html

Indeed!

named_scope :only_published, :conditions => { :published => true }

I did use that initially, but it broke my associations. After all it was
the
least work to just stick with a named_scope and double-check frontend
controllers for not showing unpublished items.

On Sat, Apr 25, 2009 at 4:57 PM, Frederick C. <

On Apr 25, 3:18 pm, Commander J. [email protected]
wrote:

Indeed!

named_scope :only_published, :conditions => { :published => true }

If you’re on 2.3 you may also be interested in the default_scope stuff
that was recently added.

Fred

Hey man,

I used something like this with great success! (so far… since I just
used like few minutes ago, nothing broke and all test passed) In
Rails 2.2.2

class << self
def find(*args)
args.first == :all ? self.with_scope(:find => {:conditions =>
[:published => true]}) {super} : super
end
end

Do test it out if you still need to. And anyone else could comment if
this is the right way to do it.

Cheers!
Arzumy MD

On Apr 29, 1:19 am, Commander J. [email protected]