1

我的 Rails 应用程序中有以下范围,用于Choices从基于current_user. 这工作得很好,但如果没有current_user代码Choices在数据库中获取所有的。在这里,我只希望它什么也得不到。

scope :active,  lambda{|user| user ? { :conditions => ["deliverydate = ? and user_id = ?", Date.tomorrow, user.id], :order => 'id DESC'} : {} }

如果没有,我该如何重写上面的内容以不返回任何内容current_user

问题是我正在使用Pusher将新数据推送到网站,但是如果用户会话过期,那么所有数据都会被推送而不是什么都没有......希望这是有道理的 :)

4

3 回答 3

4

由于作用域返回一个ActiveRecord::Relation实例,因此返回空对象会更正确,ActiveRecord::Relation就像这里描述的那样。

因此,您必须添加可以解决:none问题的范围:

scope :none, limit(0)

然后在您的范围内使用它,例如:

scope :active, ->(user = nil) { user ? { :conditions => ["deliverydate = ? and user_id = ?", Date.tomorrow, user.id], :order => 'id DESC'} : none }
于 2012-12-04T09:01:41.250 回答
2

那是因为空的hash( {})没有条件,基本上就是返回所有的行。

根据您的代码的结构方式,您可以创建一个类似于 的条件:id => -1:id => nil或者1=0总是这样的条件,false因此它不会返回任何行。

(正如您在问题下方的评论中提到的那样,范围不应返回 nil,因为它不能被链接。)

于 2012-12-04T08:44:39.420 回答
2
scope :active,  lambda{|user| user ? { :conditions => ["deliverydate = ? and user_id = ?", Date.tomorrow, user.id], :order => 'id DESC'} : nil }
于 2012-12-04T08:49:25.543 回答