0

I am writing a private messaging system for my web app. Just think of it as doing the same thing as sending PMs on your typical social networking website like Facebook or Twitter, or even sending an e-mail through Hotmail.

I have come up with the following migration so far:
class CreateMessages < ActiveRecord::Migration
  def self.up
    create_table :messages do |t|
      t.integer :sender_id, :recipient_id
      t.string :title
      t.text :body
      t.boolean :read
      t.timestamps
    end
  end

  def self.down
    drop_table :messages
  end
end

However, the sender_id and recipient_id both refer to the same field, which is the id field in the Role model. What changes do I have to make so the interpreter knows it's referring to that field. Are there other changes I have to make such as join tables?

alamodey
  • 14,320
  • 24
  • 86
  • 112
  • 1
    Please put your code into a formatted code block. It will make it much easier for people to read and understand your question. (Highlight your code and type Ctrl-K) – A. Levy Apr 18 '09 at 15:26

1 Answers1

1

If I'm reading your question correctly, you should make the change in your model using the class_name option for belongs_to:

belongs_to :sender, :class_name => 'Role', :foreign_key => 'sender_id'
belongs_to :recipient, :class_name => 'Role', :foreign_key => 'recipient_id'

I think the foreign keys are inferred, though, so you should be able to leave those off.

Raphomet
  • 3,589
  • 1
  • 23
  • 12
  • The default foreign key on a belongs_to is association_name_id, so it would guess sender_id and recipient_id in your example. – Sarah Mei Apr 18 '09 at 22:26
  • should the foreign keys be "role_id" instead? I want it to be named sender_id but how do I establish that sender_id is really referring to role_id? – alamodey Apr 19 '09 at 03:09