Skip to main content

Finding Users in Group Chat Go Rails Class

Rails • Asked by Omar Khedr

Hi guys,

I went through Chris's Go Rails course on Group Chat with Action Cable and learned loads from it. One of the things that I need some help with though is being able to find all the chatrooms associated with a current user and displaying it in my html page. I tried the following but this only gave me my currently displayed direct_message page.

My Attempt - show.html.erb

<% @chatroomall.each do |chatroom| %>
<div>
<%= @chatroom.name %>
</div>
<% end %>

direct_messages_controller.rb

class DirectMessagesController < ApplicationController
    before_action :authenticate_user!

    def show
        users = [current_user, User.find(params[:id])]
        @messageduser = User.find(params[:id])
        @chatroom = Chatroom.direct_message_for_users(users)        
        @chatroomall = Chatroom.all
        @messages = @chatroom.messages.order(created_at: :desc).limit(100).reverse
        @messagelast = @chatroom.messages.last(1)
        render "chatrooms/show"
    end
    end

Chatrooms.rb

class Chatroom < ApplicationRecord
    has_many :chatroomusers
    has_many :users, through: :chatroomusers
    has_many :messages

    scope :public_channels, ->{where(direct_message: false) }
    scope :direct_messages, ->{ where(direct_message: true) }

    def self.direct_message_for_users(users)
        user_ids = users.map(&:username).sort
        name = "#{user_ids.join(" and ")}"

        if chatroom = direct_messages.where(name: name).first
            chatroom
        else

            chatroom = new(name: name, direct_message: true)
            chatroom.users = users
            chatroom.save
            chatroom
        end

    end
end

Was able to figure it leveraging the great SO commnity. In case anyone else is stuck on a similar issue, here's a link to the solution that worked

(http://stackoverflow.com/questions/44092682/find-all-chatrooms-associated-with-a-current-user-using-group-chat-via-actioncab)


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.