views:

201

answers:

1

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?

+1  A: 

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
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
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