tom*_*all 10 arrays postgresql activerecord ruby-on-rails rails-activerecord
我有一个Rails 5应用程序,带有PostgreSQL 9.6数据库.
应用程序具有Report模型,具有department_ids数组字段,其定义schema.rb如下:
t.integer "department_ids", default: [], array: true
Run Code Online (Sandbox Code Playgroud)
我需要编写一个返回报表行的查询,其中department_ids列包含一组或多组给定的department_id.
我目前的解决方法是在Ruby中执行以下操作:
department_ids = [2, 5]
reports = Report.all.select do |report|
(report.department_ids & department_ids).any?
end
Run Code Online (Sandbox Code Playgroud)
然而,使用select具有返回的缺点Array而不是ActiveRecord::Relation,这意味着我需要将过滤后的结果水合回到ActiveRecord::Relation对象中.
Report.where(id: reports.map(&:id))
Run Code Online (Sandbox Code Playgroud)
我想避免这一步,并在一个查询中处理这一切.
如何用Active Record编写这样的查询?
pot*_*hin 11
这样的事情应该有效:
Report.where('department_ids @> ARRAY[?]::integer[]', [2, 5])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2706 次 |
| 最近记录: |