查询数组列是否包含一个或多个值

问题描述 投票:9回答:1

我有一个Rails 5应用程序,带有PostgreSQL 9.6数据库。

该应用程序具有Report模型,具有department_ids数组字段,在schema.rb中定义为:

t.integer "department_ids", default: [], array: true

我需要编写一个返回报告行的查询,其中department_ids列包含一组或多个给定的department_id。

我目前的解决方法是在Ruby中执行以下操作:

department_ids = [2, 5]

reports = Report.all.select do |report|
  (report.department_ids & department_ids).any?
end

然而,使用select有返回Array而不是ActiveRecord::Relation的缺点,这意味着我需要将过滤后的结果水合回到ActiveRecord::Relation对象。

Report.where(id: reports.map(&:id))

我想避免这一步,并在一个查询中处理这一切。

如何用Active Record编写这样的查询?

ruby-on-rails arrays postgresql activerecord rails-activerecord
1个回答
9
投票

这样的事情应该有效:

Report.where('department_ids @> ARRAY[?]::integer[]', [2, 5])
© www.soinside.com 2019 - 2024. All rights reserved.