Reputation: 1857
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 found the answer to this prior question. If this is the way to do, I'm not certain what the right migration would be to get the messages table to have the necessary columns. Do I need to migrate by both adding a column and a foreign key? Tried this and got stuck.
Another approach I thought of was to create a join table with a string attribute containing either "from" or "two." I assume then then I'd need to create my own Message.from method that searches for message_phone_numbers with "from" in some string? That feels unwieldy.
Or a third possible way... a FromPhoneNumber class and ToPhoneNumber class that has the join info.
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
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