Forum: Ruby on Rails Applying default conditions to a model's find, find_by_*

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eric M. (Guest)
on 2009-02-27 05:12
(Received via mailing list)
What is the best solution for applying a default condition to a model,
for example only records where active is boolean true?  My initial
implementation overrode the find method using with_scope to apply the
condition, but I soon discovered that didn't work with the
will_paginate plugin.

I currently have a named_scope called :active that applies the
conditions, but I'm not sure how to incorporate that so that it is
always applied to find and find_by_* without having to use it inside
of the controller.

I'd also like to apply a default sort order and have this code.  Could
I follow similar logic for applying the condition?

  def self.find(*args)
    options = args.last.is_a?(Hash) ? args.pop : {}
    if not options.include? :order
      options[:order] = 'created_at desc'
    end
    args.push(options)
    super
  end
Craig D. (Guest)
on 2009-02-27 07:47
(Received via mailing list)
If you can move to Rails 2.3, which is currently in release candidate
testing, you could use default scoping:
http://ryandaigle.com/articles/2008/11/18/what-s-n...

Regards,
Craig
Eric M. (Guest)
on 2009-02-27 22:11
(Received via mailing list)
Not at this point, so I'd prefer to come up with a solution using
2.2.2.
Maurício L. (Guest)
on 2009-02-27 22:15
(Received via mailing list)
At your model, override the find method:

class SomeModel < ActiveRecord::Base

  class << self

    def find(*args)
      with_scope( :conditions => {:property => 'value'} ) do
        super(*args)
      end
    end

  end

end


-
Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)
Eric M. (Guest)
on 2009-02-27 23:19
(Received via mailing list)
I originally used a with_scope, but that doesn't play nicely with
will_paginate.

On Feb 27, 3:14 pm, Maurício Linhares <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.