Rails 作用域对 NOT IN 值不执行任何操作
我有一个 Rails 3 范围,不包括 id 数组。
编写作用域的最佳方法是什么,以便在数组为空且仍可链接时不执行任何操作?我目前有这个,它可以工作,但似乎有点做作:
scope :excluding_ids,
lambda {|ids| ids.empty? ? relation : where('id not in (?)', ids) }
如果我没有“ids.empty??关系:”位,当ids为空时,生成的SQL
... ID not in (NULL) ...
将始终不返回任何内容。所以类似:
Model.excluding_ids([]).where('id > 0')
不返回结果。
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) }
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 ids 数组为空,则不返回任何内容。
如果没有
ids
,则查询将在没有任何附加约束的情况下运行。If the
ids
array is empty then don't return anything.The query will run without any additional constraints on the query if there are no
ids
.在 Rails 4 中你可以使用:
In Rails 4 you can use:
这是 Douglas 的答案的一个细微变化,使用 ruby 1.9 stable lambda 语法,并且在 where 方法中没有括号。
Here's a slight variation on Douglas' answer, using ruby 1.9 stabby lambda syntax and without the brackets in the where method.
下面的怎么样? (尽管它仍然检查空数组,所以如果这是你试图避免的,那并没有多大的改进:)
How about the following? (It still checks for an empty array though, so if that's what you're trying to avoid it's not much of an improvement :)