Ruby Active Record Associations in Rails More Association Options Polymorphic "Has Many" Associations

bessiebarnes
bessiebarnes
59,144 Points

How do I Update the Car and Truck model classes so that each is treated as a "vehicle" which has_many Part instances?

I'm stuck on this challenge.

Update the Car and Truck model classes so that each is treated as a "vehicle" which has_many Part instances.

class Car, Parts < ApplicationRecord # YOUR CODE HERE has_many :vehicle_id has_many :vehicle_type end

We couldn't find any association from the Car class to the Part class. <---- This is the error I got from the above code.

models/car.rb
class Car < ApplicationRecord
  # YOUR CODE HERE
 has_many :vehicle_id
 has_many :vehicle_type 
end
models/truck.rb
class Truck < ApplicationRecord
  # YOUR CODE HERE
end

2 Answers

Jake Dewan
Jake Dewan
7,653 Points

First off what you need to do is to put the "Parts" instance in the has_many and then do it as a "Vehicle" instance so your code should look like this under the Car and Truck class.

class Car < ApplicationRecord has_many :parts, :as=> :vehicle end

class Truck < ApplicationRecord has_many :parts, :as=> :vehicle end

bessiebarnes
bessiebarnes
59,144 Points

Thank you, Jake, for the help on this challenge.

Jeremiah Shafer
Jeremiah Shafer
7,382 Points

The syntax of the above code is incorrect. It should be:

class Car < ApplicationRecord
    has_many :parts, as: :vehicle
end
class Truck < ApplicationRecord
    has_many :parts, as: :vehicle
end