ai didi

ruby-on-rails - ActiveRecord 排除所有查询的结果

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:23 24 4
gpt4 key购买 nike

所以出于某种原因,我的客户不会从他们的数据库中删除不活跃的用户。有没有办法全局排除对用户表的所有 ActiveRecord 调用的所有非事件用户?

例如:User.where("status != 'Inactive'")

我希望它是全局的,这样我就不必在每个用户语句中都包含它。

最佳答案

是的,您可以设置默认范围:

class User < ActiveRecord::Base
default_scope where("status != 'Inactive'")
end

User.all # select * from users where status != 'Inactive'

...但你不应该这样做。

当您不可避免地忘记有一个默认范围并且对为什么找不到您的记录感到困惑时,这只会导致麻烦。

它还会对关联造成严重破坏,因为属于不在默认范围内的用户的任何记录都会突然看起来不属于任何用户。

如果您对帖子和用户进行了简单的设置,并且用户有一个默认范围,那么您会得到这样的结果:

# we find a post called 1
p = Post.first # <#post id=1>

# It belongs to user 2
p.user_id # 2

# What's this? Error! Undefined method 'firstname' for `nil`!
p.user.first_name

# Can't find user 2, that's impossible! My validations prevent this,
# and my associations destroy dependent records. Can't be!
User.find(2) # nil

# Oh, there he is.
User.unscoped.find(2) <#user id=2 status="inactive">

在实践中,这将一直出现。通过 ID 查找记录,然后尝试查找拥有它的关联记录以验证权限等是很常见的。您的逻辑可能会编写为假设关联记录存在,因为验证应该防止它不存在。突然间,您会发现自己遇到许多“nil 类上的未定义方法空白”错误。

明确您的范围会更好。定义一个名为 active 的用户,并使用 User.active 明确选择您的活跃用户:

class User < ActiveRecord::Base
scope :active, -> where("status != 'Inactive'")
end

User.active.all # select * from users where status != 'Inactive'

我只建议使用 default_scopeorder(:id) 应用于您的记录,这有助于 .first.last 行为更理智。我永远不会推荐使用它来默认排除记录,这让我受了太多次折磨。

关于ruby-on-rails - ActiveRecord 排除所有查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24556522/

24 4 0
文章推荐: ruby-on-rails - 在 Ruby 中找到一个数组元素并将其设置为 last?
文章推荐: ios - 在 UISplitViewController 中,无法使 showDetailViewController :sender: push onto detail navigationController
文章推荐: ios - 代码 "Message from debugger: got unexpected response to k packet: OK"
文章推荐: ruby - 如何根据 ruby​​ 中的条件加入一些(不是全部)数组元素?
数据小太阳
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com