问题
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