ruby-on-rails – 查询数组列是否包含一个或多个值
发布时间:2020-12-16 19:06:29 所属栏目:百科 来源:网络整理
导读:我有一个Rails 5应用程序,带有PostgreSQL 9.6数据库. 该应用程序具有Report模型,其中包含department_ids数组字段,该字段在schema.rb中定义为: t.integer "department_ids",default: [],array: true 我需要编写一个返回报告行的查询,其中department_ids列包
我有一个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编写这样的查询? 解决方法
像这样的东西应该工作:
Report.where('department_ids @> ARRAY[?]::integer[]',[2,5]) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |