简体   繁体   English

Rails / PostgreSQL:整数数组列中的查询值

[英]Rails/PostgreSQL : query value inside an integer array column

What I wrong with me or this query? 我错了我或这个查询?

I have a Shop model with an opening days column, which is an array of integers (something you can do with Postgres): 我有一个带有开放日期列的Shop模型,这是一个整数数组(你可以用Postgres做的事情):

days= [1,1,1,1,0,0,0]

When I query: 当我查询时:

shops = Shop.where('days[0] = 1')

I get an empty ActiveRecord Relation. 我得到一个空的ActiveRecord关系。

=> #<ActiveRecord::Relation []>

When I take a shop with this kind of array… 当我带这种阵列的商店...

shop = Shop.first
=> #<Shop id: 215, days: [1, 1, 1, 1, 0, 0, 0],…

If I do 如果我做

shop.days[0]

I get 我明白了

=> 1

I really don't get it. 我真的不明白。

By default PostgreSQL uses a one-based numbering convention for arrays, that is, an array of n elements starts with array[1] and ends with array[n] . 默认情况下, PostgreSQL对数组使用一种基于编号的约定,即n个元素的数组以array[1]开头,以array[n]结尾。

Source - 来源

It's just your example. 这只是你的榜样。 Your index is out of bounds, so it doesn't match any records, days[0] is NULL . 您的索引超出范围,因此它与任何记录都不匹配, days[0]NULL Everywhere. 到处。 Fire up rails db and figure: 启动rails db并计算:

SELECT * FROM shops WHERE days[0] IS NULL;

But what's with that "by default" ? 但是“默认情况下”是什么? Is it possible to define array bounds on schema level so this never becomes an issue? 是否可以在模式级别定义数组边界,这样这永远不会成为问题?

Well... it's Rails' fault, I'm afraid. 嗯......这是Rails的错,我很害怕。 If it's even considered an "issue" at all. 如果它甚至被认为是一个“问题”。 In order for an array to be zero-indexed it should be saved as such in SQL. 为了使数组为零索引,它应该在SQL中保存。 I tried that in SQL, it works: 我在SQL中试过它,它的工作原理是:

INSERT INTO shops
        (days,           created_at,        updated_at)
  values('[0:2]={1, 1, 0}', current_timestamp, current_timestamp);

Unfortunately, Rails loses bounds for some reason: 不幸的是,Rails由于某种原因失去了界限:

 Shop.create(days: '[0:3]={6, 7, 8, 9}')
 > INSERT ... [["days", "{6,7,8,9}"], ...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM