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

Ruby on rails ActiveRecord排除所有查询的结果,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,因此,出于某种原因,我的客户端不会从数据库中删除非活动用户。是否有一种方法可以全局排除对users表的所有ActiveRecord调用的所有非活动用户 例如:User.wherestatus!='不活跃的 我希望它是全局的,这样我就不必在每个用户语句中都包含它。当然,在您的模型中定义一个默认范围 有关更多信息,请参阅 乙二醇 是,您可以设置默认范围: class User < ActiveRecord::Base default_scope where("status != 'Inac

因此,出于某种原因,我的客户端不会从数据库中删除非活动用户。是否有一种方法可以全局排除对users表的所有ActiveRecord调用的所有非活动用户

例如:User.wherestatus!='不活跃的


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

当然,在您的模型中定义一个默认范围 有关更多信息,请参阅

乙二醇


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

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

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

我只建议使用默认的_作用域将order:id应用到您的记录中,这有助于您更理智地进行第一步和最后一步。我永远不会建议默认情况下使用它来排除记录,因为这让我痛苦太多了。

作为@meagar建议的替代方案,您可以创建一个与Users表结构相同的新表,称为InactiveUsers,并将用户移动到此处,在执行此操作时将其从用户中删除。这样,您的数据库中仍然有它们,并且可以在需要时将它们恢复到用户中。

通常知道要搜索的正确关键字:我同意这一点:设置显式范围,然后在任何地方或几乎任何地方使用它,是正确的方法。记住,可能需要阅读代码的不仅仅是您,即使是您,有时也可能会忘记。
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">
class User < ActiveRecord::Base
  scope :active, -> where("status != 'Inactive'")
end

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