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 Johnson wrote:

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

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

Indeed!

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

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

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.

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