Chat App — React.js, Ruby on Rails API and Action Cable

Zaharia Anton
2 min readDec 10, 2020

--

This will be the last post about my chat-app project. Other posts are:

Rails session does not persist?

Why I used Rails sessions instead of JWTs

After completing the registration part and I have a user that can perform different actions I could create the models that require this user:

Message

which belongs to a user and a conversation, and

Conversation

which has many messages, and also has many users, through messages.

Next steps were to set up my Serializers and whitelist action cable in config > environments > development.rb:

config.action_cable.url = “ws://localhost:3000/cable” config.action_cable.disable_request_forgery_protection = true

and also create an accessible WebSocket in my routes file.

mount ActionCable.server => ‘/cable’

Now I was ready to create my channels:

These channels are a bit confusing at the beginning but when you realise how straight forward they become simple.

How I understood what those methods are was imagining that this WebSockets channel it’s a small place which holds all the instances of the class.

The subscribed method is listening to the model or collection you describe, unsubscribe method is ending the connection and received method gets as an argument that is what it’s received new on the channel and does something with it, in the same way, a controller action does something when it’s triggered.

I think about the received method as the controlled action that fires when a new instance is created by someone else, and it was the connection to my React components.

<ActionCableConsumer/> component I got from installing

react-actioncable-provider

and including my App.js between Action Cable Provider:

<ActionCableProvider url=”ws://localhost:3000/cable”>
<App />
</ActionCableProvider>

After understanding where the data goes and comes from I handled to make an instant messages chat app.

conversations_channel{
conversation_1: {messages_channel: {message_1, message_2 ...}}
conversation_2: {messages_channel: {message_1, message_2 ...}}
conversation_3: {messages_channel: {message_1, message_2 ...}}
}

This imaginary object made me understand better the channels I was working with.

The full project can be found on this repository.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet