Activerecord Rails返回模型子集,a始终为false,a有时为true

Activerecord Rails返回模型子集,a始终为false,a有时为true,activerecord,set,ruby-on-rails-5.1,Activerecord,Set,Ruby On Rails 5.1,假设有一个模型,Users和Users的admin字段就是一个例子 查询必须始终返回admin==false的所有用户,但只有在被要求这样做时,才能返回admin==true的所有用户,但只能在一个DB请求中返回 因此,返回子集可能是: 其中A是admin==false 其中B是admin==true 返回一个或一个∪ B类似的方法应该会奏效: scope :not_admins, -> { where(admin: false) } // this is A scope :admins,

假设有一个模型,Users和Users的admin字段就是一个例子

查询必须始终返回admin==false的所有用户,但只有在被要求这样做时,才能返回admin==true的所有用户,但只能在一个DB请求中返回

因此,返回子集可能是:

其中A是admin==false

其中B是admin==true


返回一个或一个∪ B

类似的方法应该会奏效:

scope :not_admins, -> { where(admin: false) } // this is A
scope :admins, -> { where(admin: true) } // this is B

def self.example(include_admins = false)
  if include_admins
    self.not_admins.or(self.admins) // A U B
  else
    self.not_admins // A
  end
end

然后,您只需调用User.example或User.example true,这取决于您想要的是A还是U B

完美!正是我想要的。