What is the Rails way of implementing a view for a data model that contains elements with a has_many/belongs_to relationship?
Here is the model I want to show in list form:
Driver
class Driver < ActiveRecord::Base
...
has_many :cars
end
Here is the model that should be listed underneath each driver:
Car
class Car < ActiveRecord::Base
...
belongs_to :driver
end
I want to show a list of drivers with their respective cars.
This raises two questions:
1 . How do I most efficiently list both in one page? What would my controller and view have to look like? If I simply do
@drivers = Driver.all
I do not seem to get access to the cars in the view.
2 . If I only list the drivers, and load the cars upon request using AJAX, would I use a cars_controller and a drivers_controller? How would I approach writing tests for this scenario?
Expanding on what you already have:
The same can be done inversely with
@cars = Car.all.