Has Many Through Relationship using a different class name
This gave me a little bit of grief.
We are using a slightly different name. A captain of a boat is necessarily a user. But we want to call him captain (or the proverbial ‘skipper’ - this is slang for captain, for those who are not native English speakers by the way).
Hence we have this sort of relationship:
class Boat < ApplicationRecord
has_many :boat_captains
has_many :captains, through: :boat_captains, source: :user
end
class BoatCaptain < ApplicationRecord
belongs_to :boat
belongs_to :user
end
class User
has_many :boat_captains
has_many :captains, through: :boat_captains, source: :user
end
And rails does the rest.
A quick cheat sheet for us all!
Written on September 17, 2018