ActiveRecord的具有在一个表中从同一列2 FKS [英] ActiveRecord having 2 FKs from the same column in a table
问题描述
您好我想,让我的用户信息彼此,我想有一个像
Hi I want to allow my users to message each other and I thought of having a table structure like
网友: ID |名称
消息: 要|从|车身
我是比较新的轨道,我不知道我的模型看起来应该像或如何构建在那里我有来自同一第二栏FKS的关系。到&安培;从是谁发送的消息和接收器的用户。我使用的ActiveRecord我的模型。
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.
谁能帮我在正确的方向在这里指出?我有我应该使用have_many通过感觉,但我想有关系正好有2。
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.
推荐答案
您可以这样做
#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
注意:这是preferable,也建议有整数foreign_keys
。如果你想修改 foreign_keys
,我会建议的名称 sender_id
和 receiver_id
。
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
.
这篇关于ActiveRecord的具有在一个表中从同一列2 FKS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!