如何从Rails中的查询中排除一组id(使用ActiveRecord)?

Cur*_*urt 21 activerecord arel active-relation ruby-on-rails-3

我想执行一个ActiveRecord查询,该查询返回除具有某些id的记录之外的所有记录.我想要排除的ID存储在一个数组中.所以:

ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item. ???
Run Code Online (Sandbox Code Playgroud)

我不知道如何完成第二行.

背景:我已经尝试过的:

我不确定背景是否必要,但我已经尝试过.find和.where的各种组合.例如:

array_without_excluded_ids = Item.find(:all, :conditions => { "id not IN (?)", ids_to_exclude })
array_without_excluded_ids = Item.where( "items.id not IN ?", ids_to_exclude)
Run Code Online (Sandbox Code Playgroud)

这些失败了. 这个提示可能在正确的轨道上,但我没有成功地适应它.任何帮助将不胜感激.

Sco*_*ott 32

这应该工作:

ids_to_exclude = [1,2,3]
items_table = Arel::Table.new(:items)

array_without_excluded_ids = Item.where(items_table[:id].not_in ids_to_exclude)
Run Code Online (Sandbox Code Playgroud)

它完全面向对象,没有字符串:-)

  • Arel :: Table是包含列集合的数据库表的抽象.在我的系统上,我正在使用PostgreSQL,因此该列的类型为ActiveRecord :: ConnectionAdapters :: PostgreSQLColumn,它代表了我的数据库列的特征.每列包含列的名称,该列的DB类型,默认值,比例,精度特征等.我们需要一个Table实例来对ID列进行谓词匹配.'not_in'方法属于Arel :: Predications类型,它直接转换为您想要的SQL,例如"NOT IN(1,2,3)". (3认同)
  • @sinisterchipmunk这是因为为空数组生成的SQL将是`SELECT"Items".*FROM"items"WHERE"items"."id"NOT IN(NULL)`.与NULL的匹配是UNKOWN.这是一个三值逻辑问题:http://en.wikipedia.org/wiki/Three-valued_logic (3认同)

nsl*_*cum 32

Rails 4解决方案:

ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item.where.not(id: ids_to_exclude)
Run Code Online (Sandbox Code Playgroud)