Chim Kan

Joined

10 Experience
0 Lessons Completed
0 Questions Solved

Activity

Posted in Rails Association Question

I think there are multiple asks here.

Let's tackle your wish to return c.manufacturer, c.model, c.sub_model.

For only that perspective, the naive implementation is to have fields in the car table with manufacturer, model and sub_model. I'd do that if it's an MVP. Now, you can filter the results just like selecting countries > states by using JS and then pull the of manufacturer > model; then model > sub_model.
# something like this
# it pulls the list of manufacturer
Car.distinct.pluck(:manufacturer)
# Then you can do a query to find the list of model given manufacturer
# There's some performance issue, but it's a starting point
Car.select(:model).where(manufacturer: :variable_name).distinct
# Repeat for the sub model.

More elaborate implementation would have Car that has_one Manufacturer, has_one CarModel, has_one CarSubModel. Basically, you have 4 tables and they have references to each other. In that case, you avoid having to have the same manufacturer saved for each car row, but it increases the complexity of maintaining them together. The pro of this is that it avoids duplication and it make sure there is only one Audi and not many Audis.

Your requirement about able to add Cars with Manufacturer and not the Model or Sub-Model, there are variations of how that can be implemented but it's not part of the database schema design stage.