3个模型之间的关联

时间:2016-06-30 16:55:12

标签: ruby-on-rails ruby

我希望用户能够创建一个课程(因此它应该属于一个用户),并且还能够加入另一个没有由他创建的课程。课程和课程之间的正确关联是什么用户?我想制作以下模型关联:

Class User < ActiveRecord::Base
  has_many :courses
  has_many :comments ,through: :courses
end

Class Course < ActiveRecord::Base
  has_and_belongs_to_many :users    #here i am not sure
  has_many :comments
end

Class Comment < ActiveRecord::Base
  belongs_to :courses
end 

2 个答案:

答案 0 :(得分:1)

我认为你应该做的事情如下:

Class User < ActiveRecord::Base
  has_many :courses
  has_many :course_users
  has_many :subscribed_courses, through: :course_users, source: :course # I think you should be able to do foreign_key: :course_id, class_name: 'Course'
  has_many :comments ,through: :courses
end

Class Course < ActiveRecord::Base
  belongs_to :user
  has_many :course_users
  has_many :participants, through: :course_users, source: :user # I think you should be able to do foreign_key: :user_id, class_name: 'User'
  has_many :comments
end

Class Comment < ActiveRecord::Base
  belongs_to :courses
end

#course_users is a join table for courses and users
class CourseUser < ActiveRecord::Base
  # inside here you could have several other connections e.g grade of a user in a course within this join model
  belongs_to :user
  belongs_to :course
end

答案 1 :(得分:0)

如果我理解你在说什么 - 你需要有第三个模型 - 你可以称之为注册

对于课程,如果每个课程都是以用户身份创建的,您将使用belongs_to :user

您的注册模型有两个HABTAM

Class Enrollment < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_and_belongs_to_many :courses
end

(另外,如果课程不止一次提供,你必须为课程的每个实例添加一个额外的模型,注册将属于该模型,而不是课程)