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)
它完全面向对象,没有字符串:-)
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)
| 归档时间: |
|
| 查看次数: |
19738 次 |
| 最近记录: |