Ruby-on-rails activerecord 查找所有未包含在数组中的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4327202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:45:56  来源:igfitidea点击:

activerecord find all NOT included in an array

ruby-on-railsactiverecordruby-on-rails-3

提问by kjs3

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.

这是在 Rails 3 中,谷歌并没有给我太多的爱。

回答by nslocum

Rails 4 solution:

Rails 4 解决方案:

@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
  • 更改查询以使用默认索引的 ID

回答by Stéphan Kochen

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

我从来没有用字符串字段做过这个,但也许这会奏效:

@teams = Team.where("name NOT IN (?)", @team_exclude_list)