如何在ActiveRecord中排除搜索结果?

时间:2014-08-15 14:36:05

标签: ruby-on-rails activerecord

我正在尝试编写一个ActiveRecord Query,它将返回与current_user在同一方格中的所有字符和non_player_characters的记录,同时从结果中排除current_user。

class Square
  def self.characters(user)
    characters = []
    players = Character.all
    bots = NonPlayerCharacter.all
    characters << bots.find_by(x_coordinate: user.x_coordinate, y_coordinate: user.y_coordinate)
    characters << players.find_by(x_coordinate: user.x_coordinate, y_coordinate: user.y_coordinate)
  end
end

我读了rails guides,它告诉我如何从搜索结果中排除项目,但仅限于单个命令的上下文中。换句话说,在阅读之后,我无法弄清楚如何使用find_by方法链接不是条件。

1 个答案:

答案 0 :(得分:4)

find_by未返回有效记录关系,请使用您可以继续修改的where

players = Character.where(your conditions)
players = players.where.not(id: user.id)
# ...

或者,您可以构建关系,然后在该关系上调用find_by

players = Character.where.not(id: user.id)
players = players.where(some other conditions)
# ...
players.find_by(your conditions)