[英]How to setup model associations in Rails
I'm trying to create associations for three models in my Rails application. 我正在尝试在Rails应用程序中为三个模型创建关联。 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.) (当然,假设您已实例化了上述每个变量,并且具有关联的记录。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.