So what you're looking for is associating Truck
to User
multiple times, with each association playing a different role.
It's definitely possible, and quite a common way to set up associations.
However, I would definitely set it up so that the Truck
model is the child ("belongs to") the User
model, for two reasons -
A truck model should be self-contained in its knowledge. It should know who its creator, driver, and owner are. So you want those id's (foreign key references) stored on the Truck
and not the User
. Also in your case each truck can have 1 and only 1 creator, driver, or owner. (Side note: If you did have a case where a Truck could have numerous creators, drivers, and owners then this wouldn't work and you'd have to rely on a many-to-many relationship like an intermediary joining table.)
A user can inherently be associated with multiple trucks. A user could own 3 different trucks or they could own 1 truck but drive another. It makes more sense that a User
would have the has_many
relationships here.
The trick is that ActiveRecord lets you name associations anything you want. So you can try -
class Truck < ApplicationRecord
belongs_to :creator, class_name: "User", foreign_key: :creator_id
belongs_to :owner, class_name: "User", foreign_key: :owner_id
belongs_to :driver, class_name: "User", foreign_key: :driver_id
end
class User < ApplicationRecord
has_many :created_trucks, class_name: "Truck", foreign_key: :creator_id
has_many :owned_trucks, class_name: "Truck", foreign_key: :owner_id
has_many :driven_trucks, class_name: "Truck", foreign_key: :driver_id
end
In each line we override -
The class_name
, because if we didn't specify it Rails would use the associated name to guess it. So belongs_to :creator
would look for a Creator
model, instead of a User
model
The foreign_key
, because if we didn't specify it Rails would use the associated name to guess it. So belongs_to :creator
would look for for a creator_id
on this model (since it belongs to the other model). Similarly if we had has_one :creator
it would look for a creator_id
on the foreign Creator
model (or whatever is specified via class_name
).