user984621
user984621

Reputation: 48443

Rails - search through has_many association

I have these models:

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

I am trying to find out if the currently selected car has a certain service - trying to do it this way:

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

But this query doesn't work because of the wrong using model associations.

How do I find out, if the current car has some airbags?

Thank you in advance.

Upvotes: 1

Views: 1750

Answers (2)

fabriciofreitag
fabriciofreitag

Reputation: 2883

Assuming your migrations are fine

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

Upvotes: 2

lusketeer
lusketeer

Reputation: 1930

Well, from the look of the relationships, I assume that car_services is the rich join table of cars and car_service_definitions

What you can do is to set up has_many :through relationship on both car and 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

And then if you want to find airbag, it would be like this

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

But if you want to check if the car has air_bag, could just write a method like this

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

Upvotes: 0

Related Questions