Rails: Self-Referential Tables

Image for post
Image for post

How to Make It Work

Let’s go back to my users/messages example. We start out by creating a migration for the messages table that has a message, a sender id, and a recipient id. The message is just the text that the sender writes, but the sender_id and the recipient_id should be unfamiliar to you! I’ll give you a hint: They’re both ids that belong to a user in the User table!

//create_messages.rbclass CreateMessages < ActiveRecord::Migration[6.0]
def change
create_table :messages do |t|
t.text :message
t.integer :sender_id //user #1 foreign_key
t.integer :recipient_id //user #2 foreign_key
t.timestamps
end
end
end
//message.rbclass Message < ApplicationRecord
belongs_to :recipient, class_name: "User", foreign_key: "recipient_id"
belongs_to :sender, class_name: "User", foreign_key: "sender_id"
end
//user.rbclass User < ApplicationRecord
has_many :received_messages, class_name: "Message", foreign_key: "recipient_id"
has_many :sent_messages, class_name: "Message", foreign_key: "sender_id"
end

Friendships

class Friendship < ApplicationRecord
belongs_to :user
belongs_to :friend, class_name: 'User'
end

Followers

class Follow < ApplicationRecord
belongs_to :following, class_name: 'User', foreign_key: 'following'
belongs_to :follower, class_name: 'User', foreign_key: 'follower'
end

Friend Request

class FriendRequest < ApplicationRecord
belongs_to :user
belongs_to :friend, class_name: 'User'
end

Full-Stack Developer, Software Engineer, and UX/UI Aficionado

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store