gpt4 book ai didi

ruby-on-rails - ActiveRecord 中 default_scope 的替代方案

转载 作者:行者123 更新时间:2023-12-01 06:44:43 25 4
gpt4 key购买 nike

我面临着更改应用程序功能的问题,并且不得不重新编写大约 700 个现在需要限定范围的方法调用。

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

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

我真的很想从 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)

...结果仍然适用于用户但不包括默认范围?

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

最佳答案

您必须使用 with_exclusive_scope .

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

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

关于ruby-on-rails - ActiveRecord 中 default_scope 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6920648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com