开发者

Alternative to default_scope in ActiveRecord

I'm facing a problem with changing the functionality of an app and having to re-write about 700 method calls that now need to be scoped.

I've been looking into how default_scope works, and like most people I'm finding that it's close but not quite helpful for me, because I can't override it very easily.

What rails currently offers to override a default_scope is the unscoped method. The problem with unscoped is that it completely removes all scope, not just the default scope.

I'd really like some input from a Rails / ActiveRecord guru on some al开发者_StackOverflow社区ternatives.

Given this basic desired functionality...

class Model < ActiveRecord::Base
  ...      
  belongs_to :user
  ...
  default_scope where(:foo => true)
  scope :baz, where(:baz => '123')
  scope :sans_foo, without_default.where(:foo=>true)
  ...
end

Could you / how could you create a method that could remove the default scope while leaving the other scoping intact? IE, currently if you use...

user.models.unscoped.where(something)

... it's the same as calling

Model.where(something)

Is it possible to define a method that would allow you to instead do something like this...

user.models.without_default.where(something)

...where the result would still be scoped to user but not include the default scope?

I'd very, very much appreciate any help or suggestions on how such a functionality might be implemented.


You have to use with_exclusive_scope.

http://apidock.com/rails/ActiveRecord/Base/with_exclusive_scope/class

User.with_exclusive_scope do
  user.models.baz.where(something)
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜