chopper draw lion4
chopper draw lion4

Reputation: 13497

How do I exclude search results in ActiveRecord?

I am attempting to write an ActiveRecord Query which will return the records of all characters and non_player_characters in the same square as the current_user, while excluding the current_user from the result.

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

I read rails guides, it told me how to exclude items from my search results but only in the context of a single command. In other words, after reading it I could not figure out how to chain not conditions with the find_by method.

Upvotes: 1

Views: 1875

Answers (1)

numbers1311407
numbers1311407

Reputation: 34072

find_by doesnt return an active record relation, use where that you can continue to modify:

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

Alternatively you can build a relation, and then call find_by on that relation.

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

Upvotes: 4

Related Questions