【发布时间】:2018-04-27 15:45:48
【问题描述】:
我有一个带有 PostgreSQL 9.6 数据库的 Rails 5 应用程序。
应用程序有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 编写这样的查询?
【问题讨论】:
-
为什么要使用这样的字段?也许您需要在部门中定义report_id或建立多对多关联?
标签: ruby-on-rails arrays postgresql activerecord rails-activerecord