Activerecord associations and migrations

Viewed 24

I have a model Ride. A ride has one driver and one user Im trying to implement a Rating for the the rides Each Rating must belong to a ride. Id like to have the associations and models such that I can call Driver.ratings and it gives me all ratings for that driver(through the rides table) and call User.ratings gives me a list of all ratings for that user(through the rides table)

class Ride < ApplicationRecord
  belongs_to :driver, optional: true
  belongs_to :user, optional: true
end


class User < ApplicationRecord
  has_many :rides
end


class Driver < ApplicationRecord
  has_many :rides
end
1 Answers

You will have to use has_many through associations

In your Drive and User model, you can add following associations

class Driver < ApplicationRecord
  has_many :rides
  has_many :ratings, through: :rides
end

class User < ApplicationRecord
  has_many :rides
  has_many :ratings, through: :rides
end
Related