问题
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