Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从Rails中的查询中排除ID数组(使用ActiveRecord)?_Activerecord_Ruby On Rails 3_Arel_Active Relation - Fatal编程技术网

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

如何从Rails中的查询中排除ID数组(使用ActiveRecord)?,activerecord,ruby-on-rails-3,arel,active-relation,Activerecord,Ruby On Rails 3,Arel,Active Relation,我想执行一个ActiveRecord查询,返回除具有特定ID的记录之外的所有记录。我想排除的ID存储在一个数组中。因此: ids_to_exclude = [1,2,3] array_without_excluded_ids = Item. ??? 我不知道如何完成第二行 背景:我已经尝试过的: 我不确定背景是否必要,但我已经尝试了.find和.where的各种组合。例如: array_without_excluded_ids = Item.find(:all, :conditions =&g

我想执行一个ActiveRecord查询,返回除具有特定ID的记录之外的所有记录。我想排除的ID存储在一个数组中。因此:

ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item. ???
我不知道如何完成第二行

背景:我已经尝试过的:

我不确定背景是否必要,但我已经尝试了.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)
这些都失败了。可能是在正确的轨道上,但我没有成功地适应它。非常感谢您的帮助。

这应该可以:

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)

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

您也可以使用
squel
gem来完成这样的查询。 it文档,goes

Rails 4解决方案:

ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item.where.not(id: ids_to_exclude)

正如Nslocom所写,以下方法效果良好:

Item.where.not(id: ids_to_exclude)
如果您的“要排除的ID”来自查询(这里有一个示例条件),您甚至可以更进一步:

Item.where.not(id: Item.where(condition: true))
如果需要过滤其他模型,此选项非常有用:

OtherModel.where.not(item_id: Item.where(condition: true))

您是否尝试过
:条件=>[“id不在(?)、id到排除]
?请注意括号而不是大括号。在Rails 3.2.1中,我使用了这个
MyModel.order('created_at DESC')。其中('id NOT In(?),ids_to_exclude)。限制(5)
查询最近的一个rel::Table是数据库表的抽象,包含一组列。在我的系统上,我使用的是PostgreSQL,因此该列的类型为ActiveRecord::ConnectionAdapters::PostgreSQLColumn,它表示我的DB列的特征。每列都包含列的名称、该列的DB类型、默认值、比例、精度特征等。我们需要一个表的实例来与ID列进行谓词匹配。“not_in”方法的类型为Arel::predictions,它直接转换为您想要的SQL,例如“not in(1,2,3)”。@sinisterchipmunk这是因为为空数组生成的SQL将是
SELECT“Items”。*来自“Items”中的“Items”。.id“not in(NULL)
。与NULL的匹配是未知的。这是一个三值逻辑问题:更漂亮的语法:
Item.where(Item.arel\u table[:id]。不在ids\u中排除)
@marczking STRINGS?嗯。。。我感到恶心;去躺下。这太棒了。。我的用例是一个每周订单导出,带有一些疯狂的数据映射,因为我们的会计经过了很长一段时间的发展。。。我确实需要将查询作为活动记录关系返回,因为我使用了.to_csv类方法将我的电子商务订单映射到csv。由于某些原因,它不能处理数组或订单对象,只能处理活动记录关系。我一辈子都不知道如何在my.where active record SQL查询中以逗号分隔的列表形式打印我们的my ID数组。谢谢Scott Lowe这是目前为止最好的选择。