Lanny Bose
Lanny Bose

Reputation: 1857

Messaging Associations in Rails

I'm creating a Rails messaging application (using Twilio, which isn't super relevant, I suppose) which has the following models:

Contacts has many Phone Numbers, easy enough.

Messages has many phone numbers, except it's not many, it's exactly two. A from and a to.

I'd like to be able to make calls such as: @message.from.contact

Here are some approaches I've thought about:

I know I'm not posting any code. I've done some migrating and rolling back and am back to square one now...

Thanks for any help. I'm new to Stack Overflow and new to Rails, so your assistance will mean a lot!

Upvotes: 0

Views: 48

Answers (1)

Robin Fisher
Robin Fisher

Reputation: 1454

Yes, your first bullet point is the correct answer. For your Message model have attributes from_id and to_id which both reference a particular phone number. I have inferred the names of your models so you may need to correct those but in summary:

Migration should look like:

add_column :messages, :from_id, :integer
add_column :messages, :to_id, :integer

Message class should look like:

belongs_to :from_phone_number, class_name: 'PhoneNumber'
belongs_to :to_phone_number, class_name: 'PhoneNumber'

PhoneNumber class should look like:

has_many :sent_messages, class_name: 'Message', foreign_key: 'from_id'
has_many :received_messages, class_name: 'Message', foreign_key: 'to_id'

You could stub out some methods in your message class to give you the short hand methods you are looking for:

def from
  from_phone_number
end

In my view, just having from as an attribute on the model itself is not very descriptive and could mean the user or phone number.

Upvotes: 1

Related Questions