如何返回一个空的 ActiveRecord 关系? [英] How to return an empty ActiveRecord relation?

查看:15
本文介绍了如何返回一个空的 ActiveRecord 关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带 lambda 的作用域并且它接受一个参数,根据参数的值,我可能知道不会有任何匹配,但我仍然想返回一个关系,而不是一个空数组:

If I have a scope with a lambda and it takes an argument, depending on the value of the argument, I might know that there will not be any matches, but I still want to return a relation, not an empty array:

scope :for_users, lambda { |users| users.any? ? where("user_id IN (?)", users.map(&:id).join(',')) : [] }

我真正想要的是none"方法,与all"相反,它返回一个仍然可以链接的关系,但会导致查询短路.

What I really want is a "none" method, the opposite of "all", that returns a relation that can still be chained, but results in the query being short-circuited.

推荐答案

Rails 4 现在有一个正确"的机制:

There is a now a "correct" mechanism in Rails 4:

>> Model.none 
=> #<ActiveRecord::Relation []>

这篇关于如何返回一个空的 ActiveRecord 关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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