I’ve set up a messaging system between characters as follows. Each character
has_many :conversations with other characters
through: :chat_groups. Fairly standard setup I expect.
has_many :chat_groups, class_name: "Chat", foreign_key: "character_id", dependent: :destroy has_many :conversations, through: :chat_groups, source: :conversation has_many :messages, as: :messageable
has_many :chat_participants, class_name: "Chat", foreign_key: "conversation_id", dependent: :destroy has_many :characters, through: :chat_participants, source: :character has_many :messages, as: :messageable
belongs_to :character belongs_to :conversation
belongs_to :messageable, polymorphic: true
When a character (
@sender) sends a message to another character (
@recipient), I first need to check if a conversation between ONLY the two characters already exists, and if not, to create such a conversation. A conversation involving the two characters and other characters (a group chat) may already exist, and this should be rejected.
My question is, what’s the best/most efficient way to query for the existence of such a conversation?