Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

activerecord find all NOT included in an array

I have an array of team names from another part of code and I want to find all the Teams not in that array. I've tried the following and it doesn't work.

@team_exclude_list = ['Team 1', 'Team 2', 'Team 3']
@teams = Team.where("name != ?", @team_exclude_list)

This is in Rails 3 and the Googles aren't giving me much love.

like image 441
kjs3 Avatar asked Dec 01 '10 17:12

kjs3


2 Answers

Rails 4 solution:

@team_exclude_list = ['Team 1', 'Team 2', 'Team 3']
@teams = Team.where.not(name: @team_exclude_list)

Also, to speed up the query, you can:

  • create an index on name

OR

  • change the query to use IDs which are indexed by default
like image 152
nslocum Avatar answered Nov 11 '22 19:11

nslocum


I've never done this with a string field, but perhaps this will work:

@teams = Team.where("name NOT IN (?)", @team_exclude_list)
like image 64
Stéphan Kochen Avatar answered Nov 11 '22 21:11

Stéphan Kochen