开发者

Data structure which has a relationship with multiple objects

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
开发者_JS百科

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


Just have one User model with an attribute for user_type (student=0, teacher=1, faculty=2) and then all of the attributes you need (gpa, salary, etc.). If it's a student, leave the salary field NULL, if it's a teacher, leave the gpa field NULL, etc.

Then your messages table will just have sender_id and recipient_id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜