2016-07-06 82 views
1

我有这些模型:导轨 - 通过搜索的has_many协会

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 

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

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

预先感谢您。

回答

2

假设你的迁移都很好

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 
0

那么从关系上来看,我认为car_services是富人加入的cars表和car_service_definitions

你可以做的是建立两个carhas_many :through关系和car_service_definition

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 

但是,如果你想检查carair_bag,可以只写这样

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