Rails selecting record that has particular records through has_many association

14 views
Skip to first unread message

Bazley

unread,
Oct 20, 2015, 3:16:51 AM10/20/15
to Ruby on Rails: Talk
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?
Reply all
Reply to author
Forward
0 new messages