【问题标题】:Alternative to default_scope in ActiveRecordActiveRecord 中 default_scope 的替代方案
【发布时间】:2011-08-03 01:18:10
【问题描述】:

我在更改应用程序的功能时遇到了一个问题,我不得不重新编写大约 700 个现在需要限定范围的方法调用。

我一直在研究 default_scope 的工作原理,并且和大多数人一样,我发现它很接近但对我来说不是很有帮助,因为我不能很容易地覆盖它。

rails 目前提供的覆盖 default_scope 的是 unscoped 方法。 unscoped 的问题在于它完全删除了 all 范围,而不仅仅是默认范围。

我真的很想从 Rails / ActiveRecord 大师那里得到一些关于替代方案的意见。

鉴于这个基本的所需功能......

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

您/您能否创建一个可以删除默认范围同时保持其他范围不变的方法? IE,目前如果你使用...

user.models.unscoped.where(something)

...和调用是一样的

Model.where(something)

是否可以定义一种方法,让您可以改为执行类似的操作...

user.models.without_default.where(something)

...结果仍将作用于用户但不包括默认作用域?

我非常非常感谢任何有关如何实现此类功能的帮助或建议。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord scope named-scope


    【解决方案1】:

    你必须使用with_exclusive_scope

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

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

    【讨论】:

    • 我认为:a) 这已被弃用,并且 b) 这与 Rails 3 中的unscoped 做了同样的事情?
    猜你喜欢
    • 2011-10-23
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2015-03-03
    相关资源
    最近更新 更多