Rails SQL效率为where语句

时间:2011-05-03 00:53:00

标签: sql ruby-on-rails ruby-on-rails-3 performance

是否有更有效的方法来执行以下代码的Rails SQL语句?

将在整个网站上调用它来隐藏某些内容或用户,具体取决于用户是否被阻止,因此它需要相当高效,否则它也会减慢其他所有内容。

users.rb文件:

  def is_blocked_by_or_has_blocked?(user)
    status = relationships.where('followed_id = ? AND relationship_status = ?', 
          user.id, relationship_blocked).first ||
        user.relationships.where('followed_id = ? AND relationship_status = ?', 
          self.id, relationship_blocked).first
    return status
  end

在该代码中,relationship_blocked只是一个整数的抽象,以便以后更容易阅读。

在视图中,我这样称呼这个方法:

- unless current_user.is_blocked_by_or_has_blocked?(user)
  - # show the content for unblocked users here

修改

这是一个示例查询..它在找到第一个实例后停止(不需要检查反向关系)

Relationship Load (0.2ms)  SELECT "relationships".* FROM "relationships" WHERE ("relationships".follower_id = 101) AND (followed_id = 1 AND relationship_status = 2) LIMIT 1

1 个答案:

答案 0 :(得分:1)

您可以将其更改为仅运行一个查询,方法是在查询中使用IN (x,y,z)语句(通过将一组id传递给:followed_id来完成)。此外,通过使用.count,您可以绕过Rails为结果关系实例化模型实例,这将使事情更快(在内存中传递的数据更少):

def is_blocked_by_or_has_blocked?(user)
  relationships.where(:followed_id => [user.id, self.id], :relationship_status => relationship_blocked).count > 0
end

编辑 - 让它看起来双向;

Relationship.where(:user_id => [user.id, self.id], :followed_id => [user.id, self.id], :relationship_status => relationship_blocked).count > 0
相关问题