Ruby on rails - Reference the same model twice?

0 votes
asked Jan 13, 2010 by dan

Is it possible to set up a double relationship in activerecord models via the generate scaffold command?

For example, if I had a User model and a PrivateMessage model, the pm table would need to keep track of both the sender and recipient.

Obviously, for a single relationship I would just do this:

ruby script/generate scaffold pm title:string content:string user:references

Is there a similar way to set up two relations?

Also, is there anyway to set up aliases for the relations?

So rather than saying:


You can use something like:

@message.sender or @message.recipient

Any advice would be greatly appreciated.


4 Answers

0 votes
answered Jan 13, 2010 by veger

Add this to your Model

has_one :sender, :class_name => "User"
has_one :recipient, :class_name => "User"

And you are able to call @message.sender and @message.recipient and both reference to the User model.

Instead of user:references in your generate command you'd need sender:references and recipient:references

0 votes
answered Jan 23, 2011 by radmehr

hi there to have both side relation do as bellow in your both models:

class Message < ActiveRecord::Base

 belongs_to     :sender,
                :class_name => "User",
                :foreign_key  => "sender_id"

 belongs_to     :recipient,
                :class_name => "User",
                :foreign_key  => "recipient_id" 

class User < ActiveRecord::Base

  has_many      :sent, 
                :class_name => "Message",
                :foreign_key  => "sent_id"

  has_many      :received, 
                :class_name => "Message", 
                :foreign_key  => "received_id"

I hope this help you...

0 votes
answered Jan 21, 2012 by richard-jones

Here's a complete answer to this issue, in case people visiting this question are new to Ruby on Rails and having a hard time putting everything together (as I was when I first looked into this).

Some parts of the solution take place in your Migrations and some in your Models:


class CreatePrivateMessages < ActiveRecord::Migration
  create_table :private_messages do |t|
    def up
      t.references :sender
      t.references :recipient

Here you are specifying that there are two columns in this table that will be referred to as :sender and :recipient and which hold references to another table. Rails will actually create columns called 'sender_id' and 'recipient_id' for you. In our case they will each reference rows in the Users table, but we specify that in the models, not in the migrations.


class PrivateMessage < ActiveRecord::Base
  belongs_to :sender, :class_name => 'User'
  belongs_to :recipient, :class_name => 'User'

Here you are creating a property on the PrivateMessage model named :sender, then specifying that this property is related to the User class. Rails, seeing the "belongs_to :sender", will look for a column in your database called "sender_id", which we defined above, and use that to store the foreign key. Then you're doing the exact same thing 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, like this:

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'

Here you are creating a property on the User Model named :sent_private_messages, specifying that this property is related to the PrivateMessage Model, and that the foreign key on the PrivateMessage model which relates it to this property is called 'sender_id'. Then you are doing the same thing for received private messages.

This allows you to get all of a users sent or received private messages by doing something like this:


Doing either of these will return an array of instances of the PrivateMessage model.


0 votes
answered Sep 15, 2017 by bbengfort

The above answers, while excellent, do not create foreign key constraints in the database, instead only creating indexes and bigint columns. To ensure that the foreign key constraint is enforced, add the following to your migration:

class CreatePrivateMessages < ActiveRecord::Migration[5.1]
    def change
        create_table :private_messages do |t|
          t.references :sender
          t.references :recipient

        add_foreign_key :private_messages, :users, column: :sender_id, primary_key: :id
        add_foreign_key :private_messages, :users, column: :recipient_id, primary_key: :id

This will ensure that the indices get created on the sender_id and recipient_id as well as the foreign key constraints in the database you're using.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter