2016-07-06 114 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 
的方法