ActiveRecord having 2 FKs from the same column in a table

半世苍凉 提交于 2019-12-23 05:38:10

问题


Hi I want to allow my users to message each other and I thought of having a table structure like

User: ID | Name

Message: To | From | Body

I'm relatively new to rails and I'm not sure what my model should look like or how to build the relation where I have two FKs from the same column. To & From are the user who sent the message and the receiver. I'm using ActiveRecord for my models.

Can anyone get me pointed in the right direction here? I have a feeling I should be using have_many through but I would like to have the relationship has exactly 2.


回答1:


You can do like this

#user.rb
Class User < ActiveRecord::Base

has_many :messages

end

#message.rb
Class Message < ActiveRecord::Base

belongs_to :sender,class_name => "User",foreign_key => 'from'

belongs_to :receiver,class_name => "User",foreign_key => 'to'

end

Note: It is preferable and also recommended to have integer foreign_keys.If you would like to change the foreign_keys,i would recommend the names sender_id and receiver_id.



来源:https://stackoverflow.com/questions/23714766/activerecord-having-2-fks-from-the-same-column-in-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!