Ruby on Rails Tuesday, October 20, 2015

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.

character.rb

    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

conversation.rb

    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

chat.rb

    belongs_to :character
    belongs_to
:conversation

message.rb

    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.
Something like
Conversation.has(@sender).and_has(@recipient).and(has_no_more_characters)

My question is, what's the best/most efficient way to query for the existence of such a conversation?

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/62b44c03-1de3-4222-9def-4440b1ee2f7a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment