rafaelc
rafaelc

Reputation: 59274

How to make two foreign keys of same Model?

I've got a Model Message, that has message:text | date_sent:date as attributes. It should also have from_member and to_member representing the user that sent the message, and the user that received it.

How can I do that in Rails? I've read that the convention would be member_id for a ForeignKey to the model Member. But, what if I want two fields referencing Member?

Upvotes: 0

Views: 348

Answers (2)

Martin M
Martin M

Reputation: 8638

You can specify the class of the association:

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

and

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

In your database, :messages needs the attributes :from_member_id and :to_member_id

so in your migration its:

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

Upvotes: 3

coding addicted
coding addicted

Reputation: 3430

I would do something like this (adjust the typo for your needs and code clarity):

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'

Then you can do for instance:

@message.sender and @message.receiver

@member.message_sent and @member.message_reveived

For your migrations:

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

Upvotes: 2

Related Questions