如何制作相同型号的两个外键?

时间:2015-07-03 16:34:52

标签: ruby-on-rails ruby ruby-on-rails-3 model foreign-keys

我有一个模型消息,它有message:text | date_sent:date作为属性。它还应该有from_memberto_member代表发送邮件的用户以及收到邮件的用户。

我怎样才能在Rails中做到这一点?我已经读过,对于模型成员的ForeignKey,约定是member_id。但是,如果我想要两个引用Member的字段?

,该怎么办?

2 个答案:

答案 0 :(得分:2)

我会做这样的事情(根据你的需要和代码清晰度调整拼写错误):

message.rb

belongs_to :sender, foreign_key: :sender_id, class_name: 'Member'
belongs_to :receiver, foreign_key: :receiver_id, class_name: 'Member'


member.rb

has_many :message_sent, foreign_key: :sender_id, class_name: 'Message'
has_many :message_reveived, foreign_key: :receiver_id, class_name: 'Message'

然后你可以这样做:

@message.sender and @message.receiver

@member.message_sent and @member.message_reveived

对于您的迁移:

def change
  add_column :messages, :sender_id, :integer
  add_column :messages, :receiver_id, :integer
  add_index :messages, :sender_id
  add_index :messages, :receiver_id
end

答案 1 :(得分:2)

您可以指定关联的类:

class Message < ActiveRecord::Base
  belongs_to :from_member, class_name: 'Member'
  belongs_to :to_member, class_name: 'Member'
end

class Member < ActiveRecord::Base
  has_many :sent_messages, class_name: 'Message', foreign_key: :from_member_id
  has_many :received_messages, class_name: 'Message', foreign_key: :to_member_id
end

在您的数据库中,:消息需要属性:from_member_id:to_member_id

所以在您的迁移中:

def change
  add_column :messages, :from_member_id, :integer
  add_column :messages, :to_member_id, :integer

  add_index :messages, :from_member_id
  add_index :messages, :to_member_id
end