[英]How can i intersection two ActiveRecord Relation objects by rails?
I need to find the intersection result of two ActiveRecord Relation objects. 我需要找到两个ActiveRecord Relation对象的相交结果。 This is my Controller 这是我的控制器
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
But "&" method didn't work for ActiveRecord object 但是“&”方法不适用于ActiveRecord对象
This is my model 这是我的模特
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
So how can i find the intersection result between two CarInsuranceObject that one belongs_to car_insurance_type and another one that has_and_belongs_to_many car_models? 那么,如何找到两个属于一个car_insurance_type的CarInsuranceObject和另一个具有has_and_belongs_to_many car_models的CarInsuranceObject之间的相交结果?
Thanks! 谢谢!
As far as I understand, you need to query DB for CarInsuranceObject
's of specified CarInsuranceType
and CarModel
. 据我了解,你需要查询数据库的CarInsuranceObject
“指定的第CarInsuranceType
和CarModel
。 Why not to simplify all this stuff: 为什么不简化所有这些东西:
car_insurance_type_id = params[:car_insurance_type_id] || 1
car_insurance_objects_private = car_model_search.car_insurance_objects.where(car_insurance_type_id: car_insurance_type_id)
Btw, there is really long names for variables. 顺便说一句,变量确实有很长的名字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.