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

查看:212
本文介绍了如何返回一个空的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(',')) : [] }

我真正想要的是一个无的方法,一切的对面,即返回仍可链的关系,但结果在查询被短路。

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.

推荐答案

您可以添加一个名为范围无:

You can add a scope called "none":

scope :none, where(:id => nil).where("id IS NOT ?", nil)

这将会给你一个空的ActiveRecord ::关联

That will give you an empty ActiveRecord::Relation

您也可以将它添加到的ActiveRecord :: Base的在初始化(如果你想):

You could also add it to ActiveRecord::Base in an initializer (if you want):

class ActiveRecord::Base
 def self.none
   where(arel_table[:id].eq(nil).and(arel_table[:id].not_eq(nil)))
 end
end

很多方法可以得到这样的事情,但肯定不是最好的办法,以保持在code基地。我已经使用范围:无重构和发现,我需要保证一个空的ActiveRecord ::关系很短的时间,当

Plenty of ways to get something like this, but certainly not the best thing to keep in a code base. I have used the scope :none when refactoring and finding that I need to guarantee an empty ActiveRecord::Relation for a short time.

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

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