Sorry for the vague subject. I couldn’t think of a more descriptive one.
I’m working on an app in which users are able to send one another
messages. I’d like for each user to have a sent folder, as well as an
inbox. A user’s inbox should show who the message came from, and the
sent folder should show to whom it went. I want to only store one copy
of each message, and let the sender and receiver “delete” the message
independently of one another. My first stab was this (non-relevant
code omitted):
class Member < ActiveRecord::Base
has_many :mail_messages, :dependent => :nullify
has_many :sent_messages, :class_name => ‘MailMessage’,
:foreign_key => :sender_id, :dependent => :nullify
end
class MailMessage < ActiveRecord::Base
belongs_to :member
belongs_to :sender, :class_name => ‘Member’, :foreign_key =>
‘sender_id’
end
This works exactly as it should. When a user is destroyed, the
sender_id or member_id field for each message related to them is
nullified appropriately. The plan was to have a reaper run
periodically to delete rows from the mail_messages table where both
member_id and sender_id are null (in other words, both the sender and
receiver have deleted the message from their respective views).
There’s a fly in this ointment, though. If the sender is destroyed,
the sender_id field of the message is nullified, and the receiver’s
view can no longer show who the message came from. Likewise for the
sender if the receiver is destroyed.
The only solution I’ve thought of is to add two more fields to the
mail_messages table to store the sender’s and receiver’s ID - not for
purposes of associating the mail_message record to the members, but
just to be able to show who the sender and recipient are in UI views.
This strikes me as unclean, though. I’m not crazy about the idea of
duplicating information in a row. I’m hoping someone out there has a
better idea I’m not thinking of?
Thanks . . .
–
Bill K.