Arrays 使用rails 6和postgresql,使用数组项作为引用返回对象集合
使用Rail 6和postgres,我需要生成一个对象集合,使用字段关系上的项数组,返回所有具有关系的person“duplicated” 已使用此迁移创建数据库字段:Arrays 使用rails 6和postgresql,使用数组项作为引用返回对象集合,arrays,ruby-on-rails,ruby,postgresql,Arrays,Ruby On Rails,Ruby,Postgresql,使用Rail 6和postgres,我需要生成一个对象集合,使用字段关系上的项数组,返回所有具有关系的person“duplicated” 已使用此迁移创建数据库字段: t.integer :relations, array: true, null: false, default: [] ... add_index :people, :relations, using: :gin 它创建了这个表: id | name | relations | ----------------------
t.integer :relations, array: true, null: false, default: []
...
add_index :people, :relations, using: :gin
它创建了这个表:
id | name | relations |
------------------------|
1 | João | {nil,1,2,3} |
2 | Maria| {nil,1} |
我需要这样的回报,没有零
类似于可怜的sql:
SELECT id, name, '1' as relation FROM people WHERE 1 = ANY (relations)
union
SELECT id, name, '2' as relation FROM people WHERE 2 = ANY (relations)
union
SELECT id, name, '3' as relation FROM people WHERE 3 = ANY (relations);
tks:)这将为您提供预期的结果:
Person.joins(", unnest(people.relations) rel")
.where("rel is not null")
.select("people.id, people.name, rel")
(对于Postgres版本>9.4)
Person.joins(", unnest(people.relations) rel")
.where("rel is not null")
.select("people.id, people.name, rel")