has_one with two foreign keys?

前端 未结 1 957
鱼传尺愫
鱼传尺愫 2021-01-16 21:21

I have two classes Message and User. Message has sender_id and recipient_id both foreign keys for User. How to build relationship where I\'ll be able to get user for both se

相关标签:
1条回答
  • 2021-01-16 21:49

    You can use the :class_name property to set which class gets used for a foreign key:

    class Message < ActiveRecord::Base
      has_one :sender, :class_name => User
      has_one :recipient, :class_name => User
    end
    
    class User < ActiveRecord::Base
      belongs_to :sent_messages, :class_name => Message
      belongs_to :received_messages, :class_name => Message
    end
    

    Also, you say you are using sender_id and recipient_id for the foreign keys, but in your code you have :foreign_key => 'sender' and :foreign_key => 'recipient'. Have you tried changing them to :foreign_key => 'sender_id' and :foreign_key => 'recipient_id'? So:

    class Message < ActiveRecord::Base
      has_one :sender, :class_name => User, :foreign_key => 'sender_id'
      has_one :recipient, :class_name => User, :foreign_key => 'recipient_id'
    end
    
    class User < ActiveRecord::Base
      belongs_to :sent_messages, :class_name => Message, # ...etc
      belongs_to :received_messages, :class_name => Message, # ...etc
    end
    
    0 讨论(0)
提交回复
热议问题