ruby-on-railsactiverecordrails-activerecordrails-models

How to setup model associations in Rails


I'm trying to create associations for three models in my Rails application. In the application a User can access courses which have videos. How would I model this?

This is what I currently have:

class User < ApplicationRecord
 has_many :courses
 has_many :videos, through: :courses
end

class Course < ApplicationRecord
 belongs_to :user
 has_many :videos
end

class Video < ApplicationRecord
 belongs_to :course
 belongs_to :user
end

Is this the correct way to model these associations for what I want the application to be able to achieve?


Solution

  • Normally, this would look something like:

    class UserCourse < ApplicationRecord
      belongs_to :user 
      belongs_to :course 
    end
    
    class User < ApplicationRecord
      has_many :user_courses
      has_many :courses, through: :user_courses
      has_many :videos, through: :courses
    end
    
    class Course < ApplicationRecord
      has_many :user_courses
      has_many :users, through: :user_courses
      has_many :videos
    end
    
    class Video < ApplicationRecord
      belongs_to :course
      has_many :users, through: :course
    end
    

    That should let you do:

    @user.courses
    @user.videos
    @course.users
    @course.videos
    @video.course
    @video.users
    

    (Assuming, of course, you've instantiated each of the above variables and you have associated records.)