高效的rails查询包括record(返回boolean)

时间:2016-11-23 03:50:12

标签: ruby-on-rails mysql2

我的人有分数,我想要一种有效的方法来查询给定用户是否在顶级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

0 个答案:

没有答案