Rails 作用域对 NOT IN 值不执行任何操作

发布于 2024-10-29 10:51:59 字数 430 浏览 3 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

记忆で 2024-11-05 10:51:59

如果 ids 数组为空,则不返回任何内容。

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

如果没有 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?
}

The query will run without any additional constraints on the query if there are no ids.

青巷忧颜 2024-11-05 10:51:59

在 Rails 4 中你可以使用:

scope :excluding_ids, ->(ids) { where.not(id: ids) }

In Rails 4 you can use:

scope :excluding_ids, ->(ids) { where.not(id: ids) }
别把无礼当个性 2024-11-05 10:51:59

这是 Douglas 的答案的一个细微变化,使用 ruby​​ 1.9 stable lambda 语法,并且在 where 方法中没有括号。

scope :excluding_ids, ->(ids) {where("id NOT IN (?)", ids) if ids.any?}

Here's a slight variation on Douglas' answer, using ruby 1.9 stabby lambda syntax and without the brackets in the where method.

scope :excluding_ids, ->(ids) {where("id NOT IN (?)", ids) if ids.any?}
允世 2024-11-05 10:51:59

下面的怎么样? (尽管它仍然检查空数组,所以如果这是你试图避免的,那并没有多大的改进:)

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

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 :)

scope :excluding_ids,
     lambda {|ids| (ids.empty? && relation) || where('id not in (?)', ids) }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文