【问题标题】:Rails: Scope an entire modelRails:作用于整个模型
【发布时间】:2017-08-26 16:48:26
【问题描述】:

我正在想象类似这样的事情:

class User < ApplicationRecord

    default_scope -> { where(public: true) }

end

现在,无论何时访问 User 模型,它都应始终将 where(public: true) 附加到查询中。所以all 最终会变成all.where(public: true)

我正在尝试将这样的内容放入 ApplicationRecord 类中以覆盖所有继承模型的行为,因此手动覆盖不是我的选择。

【问题讨论】:

  • default_scope 对于所有继承模型是否都相同?
  • @Pavan 是的。这就是我想继承的原因:-)

标签: ruby-on-rails activerecord model scope


【解决方案1】:

如果所有继承模型的default_scope 保持不变,那么您可以考虑将其放入自定义模型中,并让所有其他模型从该模型继承

class CustomModel < ApplicationRecord
  default_scope -> { where(public: true) }
end

并让其他模型像这样从该自定义模型继承

class A < CustomModel
end

【讨论】:

  • 我不知道default_scope 的存在,但似乎我的直觉是对的 :)
【解决方案2】:

如果您的所有模型都具有public 作为属性,那么您可以通过将default_scope 添加到app/models/application_record.rb 来将default_scope 添加到所有模型上;

但是,拥有where(public: true)default_scope 在这里有点棘手,因为除非您使用unscoped 方法,否则您将无法访问数据not_public 数据:User.unscoped

话虽如此,最好添加一个范围 scope :public, -&gt; () { where(public: true) } 并在您想确保您的用户是公开的时调用它:

User.public.find_by(email: 'xxxxx')

【讨论】:

  • 我知道使用 default_scope 的好处和“风险”,但我没有将它用于我在帖子中说明的示例。我将它用于 gem -> github.com/slooob/sandboxy 但是我最终做了一些类似于将它添加到 application_record 的操作,方法是将它绑定到 gem 提供的 sandboxy 方法。 gem 要求不需要额外的范围来使其按预期工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 2011-06-04
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
相关资源
最近更新 更多