Problem

I am creating a messaging system-like feature on one of my projects. My structure is something like this:

Account
 - id
 - [...other related columns about the account class..]

Message
 - id
 - account_from
 - account_to
 - message
 - status
 - create_at
 - updated_at


Based on the structure, Message has two foreign key (account_from and account_to). Both of these are pointing to the Account model.

Using Two Foreign Keys to One Model Coming from a Single Model in Rails

Analysis

Technically, I would need a many-to-many relationship.

To solve this, we need to declare a couple of has_many and belongs_to that will be visible on the two models.

Code

For the Account model:
class Account < ActiveRecord::Base
 has_many :account_froms, :class_name => "Message", :foreign_key => :account_from_id
 has_many :account_tos, :class_name => "Message", :foreign_key => :account_to_id
 
 ....
 
end

And for the Message model:
class Message < ActiveRecord::Base
 belongs_to :account_from, :class_name => "Account", :foreign_key => :account_from_id
 belongs_to :account_to, :class_name => "Account", :foreign_key => :account_to_id
 ....
 
end

With this, I can easily use @account.account_froms and @account.account_tos to get all messages related to the said acocunt.

Summary

This may not be the cleanest structure for this messaging system-like problem. This post is a tutorial for the case wherein you'll be using two foreign keys in one model that comes from a single model.

1 comment :