如何通过rails交叉两个ActiveRecord Relation对象?

时间:2016-06-29 17:39:43

标签: ruby-on-rails ruby activerecord

我需要找到两个ActiveRecord Relation对象的交集结果。 这是我的控制器

if params.has_key?(:car_insurance_type_id)
  car_insurance_type = CarInsuranceType.find_by(id: params[:car_insurance_type_id])
else
  car_insurance_type = CarInsuranceType.find_by(id: 1)
end

@breadcrumb_title = car_insurance_type.title

car_insurance_objects_private = car_insurance_type.car_insurance_objects

if params.has_key?(:car_model_id)
  car_model_search = CarModel.find_by(id: params[:car_model_id])

  if car_model_search
    car_insurance_objects_from_model = car_model_search.car_insurance_objects
  end

end

car_insurance_objects_private = car_insurance_objects_private & car_insurance_objects_from_model

但"&"方法不适用于ActiveRecord对象

这是我的模特

class CarInsuranceType < ActiveRecord::Base

  has_many :car_insurance_objects ,dependent: :destroy

end

class CarInsuranceObject < ActiveRecord::Base

  belongs_to :insurance_company
  belongs_to :car_insurance_type
  has_and_belongs_to_many :car_models

end

class CarModel < ActiveRecord::Base

  belongs_to :car_brand
  has_and_belongs_to_many :car_insurance_objects ,dependent: :destroy

end

那么我怎样才能找到一个属于car_insurance_type的另一个CarInsuranceObject与另一个有_and_belongs_to_many car_models的CarInsurance?之间的交集结果?

谢谢!

1 个答案:

答案 0 :(得分:2)

据我了解,您需要查询指定CarInsuranceObjectCarInsuranceType的{​​{1}}的数据库。 为什么不简化所有这些:

CarModel

顺便说一句,变量确实很长。