【问题标题】:Return nil if no current_user如果没有 current_user,则返回 nil
【发布时间】:2012-11-21 20:08:53
【问题描述】:

我的 Rails 应用程序中有以下 Scope,用于根据 current_user 从数据库中获取活动的Choices。这工作得很好,但如果没有current_user,代码会在数据库中获取所有Choices。在这里,我只想让它什么都没有。

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

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

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

【问题讨论】:

  • 作用域永远不应该返回 nil:作用域应该是可链接的......

标签: ruby-on-rails scope pusher


【解决方案1】:

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

根据代码的结构方式,您可以创建类似于:id => -1:id => nil1=0 或始终为false 的条件,因此它不会返回任何行。

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

【讨论】:

    【解决方案2】:

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

    因此,您必须添加 :none 作用域来解决问题:

    scope :none, limit(0)
    

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

    scope :active, ->(user = nil) { user ? { :conditions => ["deliverydate = ? and user_id = ?", Date.tomorrow, user.id], :order => 'id DESC'} : none }
    

    【讨论】:

    • scope :none, ->{where(0)} 会更好,因为链接可能会导致不良结果。例如-> active.first, active.last 将覆盖限制为 1。
    【解决方案3】:
    scope :active,  lambda{|user| user ? { :conditions => ["deliverydate = ? and user_id = ?", Date.tomorrow, user.id], :order => 'id DESC'} : nil }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 2021-11-19
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多