ruby-on-rails - 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 中亮起红色,它告诉我“预期:=>”
这就是我难过的地方。
解决方案
问题是旧 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
电话
推荐阅读
- python - 从资源文件播放 QSound?
- angular - 更改值格式时在输入中显示 NaN
- apache-spark - 如何通过 Spark 结构化流以编程方式在 Kafka 中创建主题
- matlab - 在 Matlab 中对向量进行下采样时如何消除偏差
- dynamics-crm - CRM Dynamics - 如何重新上传属于现有报告的自定义“.rdl”文件
- amazon-redshift - 添加 2 个节点后,Redshift 免费存储不会增加
- docker-compose - 在 Docker 中将 EBS 挂载到 ELK
- git - 如何拉旧分支?
- python - 带有 miniconda python 环境的 Emacs gud-pdb
- python - 为什么当我尝试使用 find_all 函数在 Python 3.8 中使用 bs4 使用“class_”通过 css 搜索时得到一个空列表?