Overriding default_scope in Rails

纵饮孤独 提交于 2019-11-28 17:56:23
bdon

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) }

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.

use with_exclusive_scope

 Post.with_exclusive_scope { Post.find(:all) }

Scopes are meant to be composable, meaning you can combine a bunch of them and it effectively applies all the conditions. In this case ActiveRecord is just too naive to determine that the explicit condition should negate the first one. It just builds the query joining all the clauses with ANDs. For this reason default_scope has the most utility with the :order clauses which is not composable (in ActiveRecord 2.3's implementation anyway). There is more discussion here.

Also note that in Rails 3 ActiveRecord is using Arel for a lot of query construction which will greatly increase the power of ActiveRecord query generation while simplifying a lot of the internals. It's likely that with Arel will improve your situation. In the meantime I recommend not putting conditions in a default_scope unless there are rows that you really want to be invisible to your Rails app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!