如何排除IDS从查询Rails的数组(使用ActiveRecord的)? [英] How to exclude an array of ids from query in Rails (using ActiveRecord)?

查看:354
本文介绍了如何排除IDS从查询Rails的数组(使用ActiveRecord的)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个ActiveRecord查询,返回除了那些有一定IDS记录的所有记录。我想排除的ID存储在数组中。所以:

I would like to perform an ActiveRecord query that returns all records except those records that have certain ids. The ids I would like excluded are stored in an array. So:

ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item. ???

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

I'm not sure how to complete the second line.

背景:我已经尝试过什么:

我不知道背景是必要的,但我已经尝试过.find和。凡的各种组合。例如:

I'm not sure background is necessary, but I've already tried various combinations of .find and .where. For example:

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)

这些失败。 <一href="http://stackoverflow.com/questions/2580980/exclude-some-ids-from-result-in-rails-activerecord">This提示可能是在正确的轨道,但我还没有成功地适应它。任何帮助将大大AP preciated。

These fail. This tip might be on the right track, but I have not succeeded in adapting it. Any help would be greatly appreciated.

推荐答案

这应该工作:

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)

和它是完全面向对象的无弦: - )

And it's fully object-oriented with no strings :-)

这篇关于如何排除IDS从查询Rails的数组(使用ActiveRecord的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆