简体   繁体   English

检查轨道中是否存在记录

[英]check if a record exists in rails

I have a people table used to track user online activities. 我有一个用于跟踪用户在线活动的人员表。 I'd like to check if any user from a group is online or not with following query: 我想通过以下查询检查群组中的任何用户是否在线:

Person.where(:person_id => candidates, :online => true).present?

notes: candidates present the group of people; 注意:候选人在人群中出席; online attribute will be true if user is online 如果用户在线,则online属性为true

I realize such query is not efficient enough because it returns all the qualified users then check presence. 我意识到这样的查询效率不高,因为它返回所有合格的用户然后检查状态。 Is there any better way to do the same thing more efficiently? 有没有更好的方法可以更有效地完成相同的事情?

Thank 谢谢

Using a COUNT query would be more efficient: 使用COUNT查询会更有效:

Person.where(:person_id => candidates, :online => true).count

You can then just compare with 0 : 然后,您可以将其与0进行比较:

Person.where(:person_id => candidates, :online => true).count > 0

you could do something like: 您可以执行以下操作:

people = Person.select(:id, :online).where(id: candidate_ids)

then unless people.blank? 那么除非有人空白? loop through people and check whether they are online and do whatever you need to do with the people who are online. 遍历人们并检查他们是否在线,并与在线人一起做任何您需要做的事情。 Using select doesn't load the entire object, only the things you need. 使用select不会加载整个对象,只会加载您需要的东西。 Then when you say: 然后当你说:

person.online

It's not a query, you're just getting it from an array. 这不是查询,您只是从数组中获取它。 As a bonus, if you only have an individual user, .select also works with .find. 另外,如果只有一个用户,.select也可以与.find一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM