Ask A Question

Notifications

You’re not receiving notifications from this thread.

Rails Association Question

Neil Tonge asked in Rails

Hello

I have an app where I have a list of Cars. I have a form above that can filter them based on different attributes. I wish to add filtering based on their model and sub-models.

Each car already has a Manufacturer and these have models and then sub-models.

How can I structure this in Rails? Do I have a Modell and a SubModell (using those names to stop conflicting with rails own naming). or is there a better way?

I wish to be able to return the Manufacturer and Model and Sub Model directly from a car though. Like so:

c = Car.first
c.manufacturer # => "Ford"
c.model # => "Mondeo"
c.sub_model # => "Estate"

I need this to be able to allow adding Cars where I know the Manufacturer but not the Model or Sub Model.

Is this possible?

Neil, Thanks in advance

Reply

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.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.