Ask A Question

Notifications

You’re not receiving notifications from this thread.

Finding Users in Group Chat Go Rails Class

Omar Khedr asked in Rails

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
Reply

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)

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 84,387+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.