DEV Community

Velcruza
Velcruza

Posted on

How to create simple group chats using Rails

Hey! Have you ever thought about implementing group chats in your project? Well, you're in the right place. I'm going to walk you step by step through the process of creating simple group chats using Rails backend. Let's get right into it.

To start off you're going to want to setup the controllers, models and serializers for your backend using something like:

rails g resource User name
rails g resource Group name
rails g resource Message text references:user references:group
Enter fullscreen mode Exit fullscreen mode

Once you have that setup you want to go over to your User and Group models to make sure to add has_many :messages to their models. After doing that here's what your models should look like.

User:

class User < ApplicationRecord
  has_many :messages
end
Enter fullscreen mode Exit fullscreen mode

Group:

class Group < ApplicationRecord
  has_many :messages
end
Enter fullscreen mode Exit fullscreen mode

Message:

class Message < ApplicationRecord
  belongs_to :user
  belongs_to :group
end
Enter fullscreen mode Exit fullscreen mode

Next you're going to want to setup your Messages Controller with an index and create and it should look like:

class MessagesController < ApplicationController
    def index
        render json: Message.all, status: :ok
    end

    def create
        new_message = Message.create!(message_params)
        render json: new_message, status: :created
    end

    private

    def message_params
        params.permit(:group_id, :text, :user_id)
    end
end
Enter fullscreen mode Exit fullscreen mode

Now on your frontend when you fetch('/messages') with a get request it will return and array of objects (messages) that are already put in order of creation. From here you can filter this on your frontend to figure out what group/user the message belongs to. (on the other hand you can also do this on the backend with setting up custom routes and serializers to allow you to fetch to a route that will return messages that belong to a specific group). When creating a new message you just send a post request to your '/messages' with the user_id, group_id and text in the body object.

Hope this helped you a bit to get started on setting up some group chats!

Top comments (0)