Activerecord:查询其组合时所有请求属性的记录,但单个关联不具有所有属性

时间:2016-05-29 19:49:22

标签: ruby-on-rails ruby activerecord rails-activerecord

我有两个类似的模型:

class Thing < ActiveRecord::Base
  has_many :properties
end


class Property < ActiveRecord::Base
  belongs_to :thing
end

# == Schema Information
#
# Table name: properties
#
#  id            :integer          not null, primary key
#  thing_id      :integer          not null
#  property_1    :boolean
#  property_2    :boolean

我需要一种方法来查找具有任何属性字段组合的所有things,而不考虑属性记录(只要它们全部都有)。例如,我需要获取将property_1和property_2都设置为true的所有things,但它不必位于同一属性记录中。

thing = Thing.create

Property.create thing: thing, property_1: true
Property.create thing: thing, property_2: true

# I want to achieve something like this but with less queries 
# (also my actual models are of course more complex 
# so something like this is not practical nor efficient)
thing_ids = Property.where(property_1: true).pluck(:thing_id) & 
  Property.where(property_2: true).pluck(:thing_id)

通过处理activerecord产生的部分结果,在ruby中执行它相对简单,但我想让db做尽可能多的繁重工作。只有使用activerecord才能以不太笨拙的方式实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

您可以使用类似的内容在一个查询中执行此操作。

thing_ids = Thing.joins(
  'INNER JOIN properties p1 on p1.thing_id = things.id and p1.property_1 = true',
  'INNER JOIN properties p2 on p2.thing_id = things.id and p2.property_2 = true'
).pluck(:id).uniq