has_one with two foreign keys?

江枫思渺然 提交于 2019-12-01 14:52:00

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