Here is a complete answer to this question if people visiting this question are new to Ruby on Rails and have difficulty putting everything together (as I did when I first studied this question).
Some parts of the solution take place in your migrations, and some in your models:
Migrations
class CreatePrivateMessages < ActiveRecord::Migration def change create_table :private_messages do |t| t.references :sender t.references :recipient end
Here you indicate that in this table there are two columns that will be called: sender and: recipient and which contain links to another table. Rails will actually create columns for you with the names 'sender_id' and 'receient_id'. In our case, they will refer to rows in the Users table, but we indicate this in models, and not in migrations.
models
class PrivateMessage < ActiveRecord::Base belongs_to :sender, :class_name => 'User' belongs_to :recipient, :class_name => 'User' end
Here, you create a property in the PrivateMessage model with the name: sender, and then indicate that this property is associated with the User class. Rails, seeing "own_to: sender", will look in your database for a column named "sender_id", which we defined above, and use it to store the foreign key. Then you do the same for the recipient.
This will allow you to access your Sender and Recipient, both instances of the User model, through an instance of the PrivateMessage model, for example like this:
@private_message.sender.name @private_message.recipient.email
Here is your user model:
class User < ActiveRecord::Base has_many :sent_private_messages, :class_name => 'PrivateMessage', :foreign_key => 'sender_id' has_many :received_private_messages, :class_name => 'PrivateMessage', :foreign_key => 'recipient_id' end
Here you create a property in the user model called sent_private_messages, indicating that this property is associated with the PrivateMessage model and that the foreign key in the PrivateMessage model that associates it with this property is called "sender_id". Then you do the same for the private messages you receive.
This allows you to receive sent or received private messages from all users by doing something like this:
@user.sent_private_messages @user.received_private_messages
Executing any of them will return an array of PrivateMessage model instances.
....