2016-07-06 15 views
1

Ich habe diese Modelle:Rails - Suche durch has_many Verein

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 

Ich versuche, wenn das aktuell ausgewählte Auto einen bestimmten Dienst hat, um herauszufinden, - versuchen, es auf diese Weise zu tun:

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

Diese Abfrage funktioniert jedoch nicht, weil Modellzuordnungen falsch verwendet werden.

Wie finde ich heraus, ob das aktuelle Auto einige Airbags hat?

Vielen Dank im Voraus.

Antwort

2

Angenommen, Ihre Migrationen sind in Ordnung

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

Nun, aus dem Blick der Beziehungen, Ich gehe davon aus, dass car_services ist die reiche Tabelle cars verbinden und car_service_definitions

Was Sie tun können, ist einrichten has_many :through Beziehung sowohl car und 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 

Und dann, wenn Sie Airbag finden wollen, würde es sein, diese

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

Aber wenn Sie wollen zu prüfen, ob die carair_bag hat, könnte nur eine Methode schreiben wie diese

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