繁体   English   中英

Rails - 通过 has_many 关联搜索

[英]Rails - search through has_many association

我有这些模型:

class Car < ActiveRecord::Base
  has_many :car_services
end
class CarService < ActiveRecord::Base
  belongs_to :car
  belongs_to :car_service_definition
end
class CarServiceDefinition < ActiveRecord::Base
  has_many :car_services
end

我试图找出当前选择的汽车是否有某种服务 - 尝试这样做:

airbag = car.car_services.car_service_definitions.where('service_type = "Airbag"').first

但是由于使用模型关联错误,此查询不起作用。

我如何知道当前的汽车是否有一些安全气囊?

提前谢谢你。

假设你的迁移没问题

class Car < ActiveRecord::Base
  has_many :car_services
end

class CarService < ActiveRecord::Base
  belongs_to :car
  belongs_to :car_service_list
  has_and_belongs_to_many :car_service_definitions
end

class CarServiceDefinition < ActiveRecord::Base
end

airbag = car.car_services.car_service_definitions.where(service_type: 'AirBag').first

好吧,从关系的角度来看,我假设car_servicescarscar_service_definitions的丰富连接表

您可以做的是在carcar_service_definition上设置has_many :through关系

class Car < ActiveRecord::Base
  has_many :car_services
  has_many :car_service_definitions, through: :car_services
end

class CarService < ActiveRecord::Base
  belongs_to :car
  belongs_to :car_service_definition
end

class CarServiceDefinition < ActiveRecord::Base
  has_many :car_services
  has_many :cars, through: :car_services
end

然后如果你要找安全气囊,就是这个样子

airbag = car.car_service_definitions.where("car_service_definitions.service_type" => 'AirBag').first

但是如果你想检查car是否有air_bag ,可以写一个这样的方法

class Car < ActiveRecord::Base
  def has_air_bag?
    car_service_definitions.where("car_service_definitions.service_type" => 'AirBag').count > 0
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM