I’m trying to figure out the best way to represent the following data structures and relationships.
data models
Student
name, gpa, etc
Teacher
name, salary, etc
Faculty
name, etc
Message
from
to
My issue is that student, teacher, or faculty, could be the sender or receiver for a given message.
Naive Solution 0
Use a bunch of join tables! student_join_messages, teacher_join_messages, ….
Problem: You need to have the join go both ways (from and to), then in order to find the other half of the equation you’d have to look in 3 join tables (in this case) looking for the relationship.
Naive Solution 1
Message
from_id
from_type
to_id
to_type
Then the model could just interpret type as which model (Student=0, Teacher=1, …) and then use the id to look it up.
Problem: that isn’t very clean code and each model would need to implement its own messages relationship. (not to mention this seems very slow)
def messages
Message.where(:from_id => self.id, :from_type => 1
end
(or something like that)
So what is the proper solution for this?
(any help on how to better describe this question would be appreciated)
You need polymorphic associations: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations