简体   繁体   中英

Twice belongs_to maps back to the same table 'User'

class Comment < ActiveRecord::Base
   belongs_to :commenter, :class_name => "User", :foreign_key => "commenter_user_id"
   belongs_to :student, :class_name => "User", :foreign_key => "student_user_id"

They both belong to User.

I get it if this is done once because it helps to make it more clearer or whatnot ...

But why twice to map it back to the same table?!?!?

So, as result Comment columns are this:

  [0] "id",
  [1] "comment",
  [2] "student_user_id",
  [3] "commenter_user_id",
  [4] "created_at",
  [5] "updated_at",
  [6] "partnership_id"

Please excuse this if it seems same as my previous question. For me, it's not. Or maybe I didn't get it clearly enough. Hm.

A Comment can be posted by a Commentator who is a User and a Comment can also be posted by a Student who is also a User So it is best to define like your way

class Comment < ActiveRecord::Base
   belongs_to :commenter, :class_name => "User", :foreign_key => "commenter_user_id"
   belongs_to :student, :class_name => "User", :foreign_key => "student_user_id"

rather than just defining like this

class Comment < ActiveRecord::Base
   belongs_to :commenter
   belongs_to :student

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM