SQLite3::SQLException:没有这样的函数:REGEXP rails rspec

SQLite3::SQLException: no such function: REGEXP rails rspec

在我的项目中,我有不同的时间片。这些时间片有“00-04”、“04-08”、“08-12”、“12-16”、“16-20”、“20-24”等名称。我想获得具有上述名称的所有时间片对象。所以,我编写了以下程序:

time_slice_names = ["00-04", "04-08", "08-12", "12-16", "16-20", "20-24"]
time_slices = TimeSlice.where('name REGEXP ?', time_slice_names.join("|"))

time_slices 在我的开发模式中给了我正确的对象。但是,当我 运行 测试时,出现错误:

 ActiveRecord::StatementInvalid:
 SQLite3::SQLException: no such function: REGEXP: SELECT "time_slices".* FROM "time_slices"  WHERE (name REGEXP '00-04|04-08|08-12|12-16|16-20|20-24')

我的database.yml如下:

  development:
    adapter: mysql2
    database: development 
    encoding: utf8
    pool: 5
    timeout: 5000

  test:
    adapter: sqlite3
    database: db/test.sqlite3
    pool: 5
    timeout: 5000

我知道我的测试环境使用 sqlite3 而我的开发环境使用 mysql2。无论如何,我可以在 mysql2 和 sqlite3 上执行上述查询吗?

所以根据How to turn on REGEXP in SQLite3 and Rails 3.1?中的不同答案,regexp()在Sqlite3中默认没有定义。您必须安装将此功能添加到 Sqlite3 的本机扩展。

但是,您的查询可以在不使用正则表达式的情况下完成。

time_slice_names = ["00-04", "04-08", "08-12", "12-16", "16-20", "20-24"]
time_slices = TimeSlice.where(name: time_slice_names)

内部数据库适配器(mysql 或 sqlite3)应该理解这一点并将其转换为支持 where field in (x, y, z) 查询。

更多信息可用