Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding default_scope in Rails

Tags:

In my Post.rb model, I have default_scope :conditions => {:deleted => 'false'}

But if I try to run Post.find(:all, :conditions => "deleted='false'"), it won't return anything. It's as if the default_scope takes precedence over everything.

I want it so that when I do Post.find() it doesn't return deleted posts, but I'd also like to be able to access them if I need to. What needs to be changed in either my query or my Rails model?

Thanks.

like image 862
Jess Avatar asked Jan 15 '10 17:01

Jess


2 Answers

This one was somehow left hidden :)

Just use Post.unscoped.where(:deleted => true), if you're using Rails 3

Credit goes to José Valim for this.

like image 116
edgerunner Avatar answered Nov 13 '22 03:11

edgerunner


with_exclusive_scope is protected, so you have to create a class method:

def self.include_deleted_in
  Event.with_exclusive_scope { yield }
end

then in your controller call

Post.include_deleted_in { Post.find(:all) }
like image 37
bdon Avatar answered Nov 13 '22 03:11

bdon