0

我有两个类消息和用户。消息具有 user 的 sender_id 和 recipient_id 两个外键。如何建立关系,我将能够为发件人和收件人获取用户,例如 @message.sender.name 和 @message.recipient.name

我试图通过这种方式做到这一点:

class Message < ActiveRecord::Base  

  belongs_to :sender, :class_name => 'User', :foreign_key => 'sender'
  belongs_to :recipient, :class_name => 'User', :foreign_key => 'recipient'

end   

class User < ActiveRecord::Base

  has_many :recivied_messages, :class_name => 'Message', :foreign_key => 'recipient'
  has_many :send_messages, :class_name => 'Message', :foreign_key => 'sender'
end

但这并没有帮助,例如,当我尝试访问 @message.recipient.name 时,它​​说“未定义的方法‘名称’”

4

1 回答 1

2

您可以使用该:class_name属性来设置哪个类用于外键:

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

此外,您说您正在使用sender_idandrecipient_id作为外键,但在您的代码中,您有:foreign_key => 'sender'and :foreign_key => 'recipient'。您是否尝试将它们更改为:foreign_key => 'sender_id'and :foreign_key => 'recipient_id'?所以:

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
于 2010-08-03T04:36:17.623 回答