高效的导轨查询包括记录(返回布尔值)



我的员工有分数,如果给定的用户在顶级X用户中,我希望有一个有效的方法来查询。

# person.rb
class Person
  scope :top_score, -> {order('score DESC')}
  scope :page_limit, -> { limit(10) }
  def self.in_top_score(id)
    top_score.page_limit.something_something_soemthign?
  end
end

以前正在这样做:

user.id.in?(top_score.page_limit.pluck(:id))

,但我宁愿将此支票移至数据库,以防止对象序列化数百/数千条记录。

Person.order('score DESC').select([:score, :id]).limit(1)
Person Load (0.5ms)  SELECT score, id FROM `people` ORDER BY score DESC LIMIT 1
=> [#<Person id: "dxvrDy...", score: 35>]

现在检查该列表中是否存在另一个用户^^

Person.order('score DESC').select([:score, :id]).limit(1).exists?({id: "c_Tvr6..."})
Person Exists (0.3ms)  SELECT 1 AS one FROM `people` WHERE `people`.`id` = 'c_Tvr6...' LIMIT 1 
=> true

返回true,但应返回false

更新答案

对不起,我的原始答案不正确。(exists?查询显然使用LIMIT 1并从page_limit范围覆盖LIMIT 10,显然也抛出了ORDER BY子句。完全错误!:p)

) )

这呢?它的优雅程度不那么优雅,但我这次实际上测试了答案:p,似乎可以根据需要工作。

def self.in_top_score?(id)
  where(id: id).where(id: Person.top_score.page_limit).exists?
end

这是我的测试(使用Rails 4.2.6)及其生成的SQL(使用子查询)的示例用法:

pry(main)> Person.in_top_score?(56)
  Person Exists (0.4ms)  SELECT  1 AS one FROM "people" WHERE "people"."id" = $1 AND "people"."id" IN (SELECT  "people"."id" FROM "people"  ORDER BY "people"."score" DESC LIMIT 10) LIMIT 1  [["id", 56]]
=> false

在我的测试中,与您的原始版本相比,这确实确实具有至少具有性能的提升。


原始答案

top_score.page_limit.exists?(user.id)

http://apidock.com/rails/activerecord/findermethods/exists?

最新更新