数组数据类型的数据库查询收到错误:没有运算符匹配给定的名称和参数类型

时间:2017-01-26 16:29:30

标签: ruby-on-rails postgresql rails-activerecord

我的网球日历模型将周属性设置为数组数据类型,因为锦标赛可以持续两周。例如,第一个元素如下:

2.3.1 :001 > AtpCalendar.first
  AtpCalendar Load (0.8ms)  SELECT  "atp_calendars".* FROM "atp_calendars" ORDER BY "atp_calendars"."id" ASC LIMIT $1  [["LIMIT", 1]]
 => #<AtpCalendar id: 1, name: "Brisbane", category: "ATP 250", week: [1], created_at: "2017-01-25 17:29:36", updated_at: "2017-01-25 17:29:36">

如果我在Postgresql中查询周属性的类型,我会得到预期的答案:

2.3.1 :001 > AtpCalendar.first.week == [1]
  AtpCalendar Load (0.8ms)  SELECT  "atp_calendars".* FROM "atp_calendars" ORDER BY "atp_calendars"."id" ASC LIMIT $1  [["LIMIT", 1]]
 => true
2.3.1 :001 > AtpCalendar.first.week.class
  AtpCalendar Load (0.9ms)  SELECT  "atp_calendars".* FROM "atp_calendars" ORDER BY "atp_calendars"."id" ASC LIMIT $1  [["LIMIT", 1]]
 => Array 

到目前为止没有问题。
但是,如果我查询Postgres特定的周值,例如[1],我会收到错误:

2.3.1 :002 > AtpCalendar.where('week = ?', [1])
  AtpCalendar Load (1.7ms)  SELECT "atp_calendars".* FROM "atp_calendars" WHERE (week = 1)
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: integer[] = integer
LINE 1: ...LECT "atp_calendars".* FROM "atp_calendars" WHERE (week = 1)
                                                                   ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

我也尝试过不同的查询,但结果是一样的:

2.3.1 :001 > AtpCalendar.where("week @> ?", 1)
  AtpCalendar Load (1.6ms)  SELECT "atp_calendars".* FROM "atp_calendars" WHERE (week @> 1)
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: integer[] @> integer
LINE 1: ...ECT "atp_calendars".* FROM "atp_calendars" WHERE (week @> 1)
                                                                  ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

我可能错过了什么,但我不明白。
使用查询AtpCalendar.find_by(week: [1])

时出现相同的错误

1 个答案:

答案 0 :(得分:1)

我假设它实际上是db中的一个字符串?

AtpCalendar.where(week: '[1]')