Ruby on Rails Double Association

白昼怎懂夜的黑 提交于 2019-12-24 12:29:57

问题


I have a student that can have many comments left about them:

class Student < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :student
end

The comment, however, needs to belong to the student to whom it is about but also belong to the student that made the comment. That is, the comment needs to belong to two different students at the same time.

How can this be achieved?


回答1:


In the comments table, you should have a commenter_id and a student_id so a comment can belong to a commenter and also a student.

class Comment < ActiveRecord::Base
  belongs_to :student
  belongs_to :commenter, class_name: 'Student'
end


来源:https://stackoverflow.com/questions/15731484/ruby-on-rails-double-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!