yellowreign
yellowreign

Reputation: 3638

Getting "Not In" to Work in Rails MySQL Query

I have three models - User. Game, and Activity. I have a view that is supposed to show games where the user has no Activity records. I'm having trouble figuring out how to write the query that excludes Games that already have activity.

When I do these two versions (in the Controller), it does not work (I receive the error undefined method 'game_id' for #<ActiveRecord::Relation:0x69eab40>)

version 1

def index
  if current_user
    @activities = current_user.activities.game_id
    @games = Game.where("id NOT IN (?)", @activities )
  end
end

version 2

def index
  if current_user
    @activities = current_user.activities
    @activity_ids = @activities.game_id
    @games = Game.where("id NOT IN (?)", @activity_ids )
  end
end

However, when I do this it works: The controller:

def index
  if current_user
    @activities = current_user.activities
    @games = Game.where("id NOT IN (?)", @activities.collect {|p| p.game_id} )
  end
end

I'm worried about doing it this way because I'm not sure how scalable it is. I got the idea to do it from this [question], but in along with the answers people said that this solution was not scalable (which was not an issue for that question asker).1

Upvotes: 0

Views: 77

Answers (1)

jvnill
jvnill

Reputation: 29599

your error is not in that line. what's causing your error is this

@activities = current_user.activities.game_id

current_user.activities is an ActiveRecord::Relation object so calling game_id on it raises an exception. Your solution that works is fine since you're going to use @activities (you're going to, right?). If you want a more sql approach, try

def index
  if current_user
    @activities = current_user.activities
    @games = Game.where("id NOT IN (?)", @activities.uniq.pluck(:game_id))
  end
end

Upvotes: 1

Related Questions