Cruz Nunez
Cruz Nunez

Reputation: 3149

has_many and belongs_to with join table

I have Users and Trucks. I want the ability to say @truck.drivers << @users and @user.truck = @truck.

The solution is simple until I want the relationship to be stored in a join table.

# tables
:users
  :id

:truck_drivers
  :user_id
  :truck_id

:truck
  :id

I've gotten it to where I can say @truck.drivers << @user and @user.trucks << @truck, but I would like to limit a user to occupy one truck at a time, for my sanity.

Is it possible? A has_many/belongs_to with a join table? Or should I try a different approach? I'm not using a third model for the join table. It's just a table. Here's what I have so far.

class User < ApplicationRecord
  has_and_belongs_to_many :trucks,
    join_table: :truck_drivers, # points to the table
    class_name: :Truck # looks for the truck model in the table
end

class Truck < ApplicationRecord
  belongs_to :company
  has_and_belongs_to_many :drivers,
    join_table: :truck_drivers,
    class_name: :User
end

The reason I need a join table in the first place is because each User can have many Roles: Admin, Manager, Driver, Customer Service, etc. I thought it didn't make sense to add a truck_id to all the users if all the users are not going to be using trucks.

Upvotes: 1

Views: 1537

Answers (2)

jvillian
jvillian

Reputation: 20253

It seems like you ought to be able to do something like:

@user.trucks << @truck unless @user.trucks.any?

Upvotes: 1

Blair Anderson
Blair Anderson

Reputation: 20181

Yes this is a standard strategy with rails using the :through keyword.

rails documentation: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Make a model called TruckUser with truck_id and user_id

then edit your classes:

class User < ApplicationRecord
  has_many :truck_users
  has_many :trucks, through: :truck_users
end

class Truck < ApplicationRecord
  belongs_to :company
  has_many :truck_users
  has_many :drivers, through: :truck_users
end

class TruckUser < ApplicationRecord
  belongs_to :truck
  belongs_to :user
end

Upvotes: 0

Related Questions