简体   繁体   中英

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?

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM