I’m building an application and am a bit stuck on how to work out the
associations. It goes like this:
User :has_many vehicles
User :has_many logs
Vehicle :has_many logs
User -> Vehicles -> Logs
The Vehicles have a user_id attribute.
The Logs have user_id and vehicle_id attributes.
I see two possible scenarios here. Neither is wrong, They depend on
behavior you want.
Users have many vehicles and vehicles have many logs.
Users have many vehicles through logs.
In scenario (1) you would need two one-to-many associations:
User
has_many :vehicles
Vehicle
belongs_to :user
has_many :logs
Log
belongs_to :user
Logs would now indirectly belong to a user because vehicles belong to
users. Therefore Log would have only a foreign key to vehicle, but no
foreign key to user since that would be redundant.
Find the User for a Log with:
user = my_log.vehicle.user
In scenario (2) there would be a many-to-many association between User
and Vehicle with Log joining them.
User
has_many :logs
has_many :vehicles, :through => :logs
This scenario could be read as Users have many vehicles and vehicles can
belong to many users, where logs track the association and can store
information pertaining to a specific vehicle belonging to a specific
user.
I’m guessing this is not the scenario you want, but this pattern
certainly has its uses.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.