首页 > 解决方案 > Rails 5:如何将此 named_scope 转换为范围

问题描述

我希望是个简单的问题。

如何将此 named_scope 线从 rails 2 应用程序转换为 rails 5 的范围线

原来的...

  named_scope :effective_on, lambda { |date|
    { :conditions => ['(effective_on IS NULL OR effective_on <= ?) AND (ineffective_on IS NULL OR ineffective_on > ?)', date, date] }
  }

我已经尝试过了,但它只是将条件行打印为字符串......

  scope :effective_on, lambda { |date|
    { :conditions => ['(effective_on IS NULL OR effective_on <= ?) AND (ineffective_on IS NULL OR ineffective_on > ?)', date, date] }
  }

我怀疑这是因为 Rails 5.0 不推荐使用“条件”,但是当我尝试在这个版本中用“where”替换它时,它在我面前爆炸了......

  scope :effective_on, lambda { |date|
    { where('(effective_on IS NULL OR effective_on <= ?) AND (ineffective_on IS NULL OR ineffective_on > ?)', date, date) }
  }

...在我的脸上爆炸:整个“where”行在我的 IDE 中亮起红色,它告诉我“预期:=>”

这就是我难过的地方。

标签: ruby-on-railsruby-on-rails-5ruby-on-rails-2

解决方案


问题是旧 Rails 版本中的范围返回了一个哈希,{ :conditions => 'some conditions }但在新版本中它返回一个活动记录关系(如方法的返回值where

所以你必须改变:

scope :effective_on, lambda { |date|
  { :conditions => ['(effective_on IS NULL OR effective_on <= ?) AND (ineffective_on IS NULL OR ineffective_on > ?)', date, date] }
}

scope :effective_on, lambda { |date|
  where('(effective_on IS NULL OR effective_on <= ?) AND (ineffective_on IS NULL OR ineffective_on > ?)', date, date)
}

没有{ }那个where电话


推荐阅读