Rails 5中如何将Rails 2废弃的find(:all, conditions)转换为where查询
Rails 2 废弃查询语法转 Rails 5 正确写法
正确转换结果
你给出的Rails 2代码正确转换为Rails 5 where写法如下:
# 返回满足条件的所有Program记录的ActiveRecord关系对象,可直接链式调用其他查询方法 Program.where(volunteer: true) # 如果需要立即加载所有记录返回数组,可以加.to_a Program.where(volunteer: true).to_a
原有写法的错误原因
find(:all)本身从Rails 3开始就已经被废弃,Rails 5已经完全移除了该用法where是ActiveRecord模型类的直接调用方法,不需要作为参数传入find方法
常见conditions转where示例
以下是高频转换场景参考:
- 多相等条件查询
原Rails 2写法:
Program.find(:all, :conditions => {:volunteer => true, :status => 'published'})
Rails 5写法:
Program.where(volunteer: true, status: 'published')
- 范围查询
原Rails 2写法:
Program.find(:all, :conditions => ["age > ? AND created_at < ?", 18, '2023-01-01'])
Rails 5写法:
Program.where("age > ? AND created_at < ?", 18, '2023-01-01') # 或更安全的哈希范围写法 Program.where(age: 18..Float::INFINITY, created_at: ..Time.parse('2023-01-01'))
- IN查询
原Rails 2写法:
Program.find(:all, :conditions => {:city => ['北京', '上海', '深圳']})
Rails 5写法:
Program.where(city: ['北京', '上海', '深圳'])
- 否定查询
原Rails 2写法:
Program.find(:all, :conditions => ["volunteer != ?", true])
Rails 5写法:
Program.where.not(volunteer: true)
参考资料建议
直接查阅Rails官方Active Record查询指南即可,里面覆盖了所有where相关的用法和示例,内容准确性远高于第三方整理内容。
内容的提问来源于stack exchange,提问作者thefonso
相关产品推荐
相关产品推荐

