views:

30

answers:

1

I need to relate a Comments model with two ids at the same time but can't figure out how. Here' my situation. I am building an on-line school grading system and need to be able let the teacher make a comment on a particular student in a particular course for a particular term (grading period).

class Course
  has_many :course_terms
  has_many :enrollments
end

class CourseTerm
  belongs_to :course
end

class Student
  has_many :enrollments
  has_many :courses, :through => :enrollments
end

class Enrollment < ActiveRecord::Base
  belongs_to :student
  belongs_to :course
end

class Comment < ActiveRecord::Base
  belongs_to  :commentable, :polymorphic => true
end

I know it looks awfully complex but its pretty simple really. A course has many terms which a student can be enrolled in. I want to have comments for a CourseTerm + Student but I don't know if Polymorphic can handle multiple IDs in one comment. Can I do something like this:

class CourseTerm
  has_many :comments, :as => :commentable, :source => [:student, :course_term]
end

Or do I have to forgo Polymorphics and go with a standard Comment table build with a CourseTerm.id and Student.id?

+1  A: 

No, you won't be able to create the mapping you want using polymorphic relationships. The idea behind polymorphic relationships is to allow a model to belong to one of several other models using a single foreign key, with the addition of an extra column that indicates the model that each row refers to. For comments, the table would look something like:

CREATE TABLE comments (
    id                integer primary key,
    commentable_id    integer,
    commentable_type  varchar(255),
    text              text
);

But since you want to associate your comments with both users and course terms, a single foreign key is not enough, so you have to use a standard model that belongs to both users and course terms:

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :course_term
end
Pär Wieslander
Darn you and your logic. :) I was hoping that Rails might have some more *magic* in its pouch to make this all just work. Oh well, it looks like I have to do it the hard way.Thanx for the help!
RNHurt