[英]ActiveRecord::StatementInvalid (PG::UndefinedFunction
I have a checkbox field (car_options) that stores an array of values for a number of selections. 我有一个复选框字段(car_options),该字段存储许多选择的值数组。
I need to query all Car records that contain any of the values in another array. 我需要查询包含另一个数组中任何值的所有Car记录。
["a","b","c","d","e","f"] that contains any of the following ["b", "z","v"] [“ a”,“ b”,“ c”,“ d”,“ e”,“ f”]包含以下任何[[b],“ z”,“ v”]
t.string "car_options", default: [], array: true
Check if attr array contains any of element from given array in Rails 检查attr数组是否包含Rails中给定数组的任何元素
Car.where('car_options && ARRAY[?]', ["4door","3seat"])
ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR: operator does not exist: character varying[] && text[]) LINE 1: ...cars".* FROM "cars" WHERE (car_options && ARRAY['...^ ActiveRecord :: StatementInvalid(PG :: UndefinedFunction:错误:运算符不存在:字符变化[] && text [])第1行:... cars“。* FROM” cars“其中(car_options && ARRAY ['... ^
HINT: No operator matches the given name and argument types. 提示:没有运算符匹配给定的名称和参数类型。 You might need to add explicit type casts. 您可能需要添加显式类型转换。 : SELECT "cars".* FROM "cars" WHERE (car_options && ARRAY['BY']) LIMIT $1 :从“汽车”中选择“汽车”。*(car_options && ARRAY ['BY'])LIMIT $ 1
PostgreSQL is complaining because ARRAY[?]
ends up being a text[]
(ie an array of text
) where as your car_options
column is character varying[]
(ie array of character varying
). PostgreSQL抱怨是因为ARRAY[?]
最终是text[]
(即text
的数组),其中car_options
列的character varying[]
是car_options
character varying[]
(即character varying
数组)。
You could cast the array literal: 您可以转换数组文字:
Car.where('car_options && ARRAY[?]::varchar[]', ["4door","3seat"])
or make the column text[]
: 或将列设为text[]
:
t.text "car_options", default: [], array: true
I'd probably go with the latter because PostgreSQL handles text
and character varying
types the same internally, the only time you'd bother with varchar
(AKA character varying
or t.string
in a migration) is if you have a hard limit on how long they should be (and even then you could use text
with a CHECK constraint). 我可能会选择后者,因为PostgreSQL在内部以相同的方式处理text
和character varying
类型,因此您唯一一次对varchar
(AKA character varying
或迁移中的t.string
)感到烦恼的是,如果您对如何它们应该是多长(即使这样,您也可以使用带有CHECK约束的text
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.