Rails的范围,什么也不做对未在值 [英] Rails scope that does nothing for NOT IN values

查看:151
本文介绍了Rails的范围,什么也不做对未在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails 3的范围排除ID数组。

I have a Rails 3 scope that excludes an array of ids.

什么是如此,它什么都不做,当数组是空的,仍然可链接写入范围的最佳方法是什么?我现在有这个,它的工作原理,但似乎有点做作:

What is the best way to write the scope so that it does nothing when the array is empty and is still chainable? I currently have this, which works, but seems a little hokey:

scope :excluding_ids, 
         lambda {|ids| ids.empty? ? relation : where('id not in (?)', ids) }

如果我没有ids.empty关系:??位,当id为空,生成的SQL是

If I do not have the "ids.empty? ? relation :" bit, when ids is empty the SQL generated is

... ID not in (NULL) ...

这将不可能有返回结果。所以是这样的:

which will always return nothing. So something like:

Model.excluding_ids([]).where('id > 0')

不返回任何结果。

returns no results.

推荐答案

如果在 IDS 数组为空,那么不返回任何东西。

If the ids array is empty then don't return anything.

scope :excluding_ids, lambda { |ids|
  where(['id NOT IN (?)', ids]) if ids.any?
}

查询将在查询运行,没有任何额外的限制,如果没有 IDS

这篇关于Rails的范围,什么也不做对未在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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