Gmail Like Chat Application in Ruby on Rails

Gmail Like Chat Application in Ruby on Rails

___

In this tutorial, I will guide you on how to implement a Gmail/Facebook like real-time chat application in a Ruby on Rails application.

Introduction

We are all fond of the Gmail and Facebook inline chat modules. About a week ago, I came across a tutorial on how to replicate hangouts chat in pure css and html and this really inspired me. I thought to myself, "why not give life to this beautiful Gmail-like chat UI?". With this, I challenged myself to try and come up with a real-time chat in a Rails application. I wanted to have a near-realtime kind of chat functionality and in my research I found out that the publish/subscribe model was the most efficient, fast and scalable way to go about this.

As a framework, Rails is not very good at handling asynchronous events and therefore establishing a socket connection to a Rails application is almost impossible. There are many solutions that are designed to handle this kind of problem. Frameworks such as Node.js with Socket.IO, or, if you want to stick with Ruby, Cramp, async_sinatra, or Goliath framework are all great solutions but it would be super awesome to continue using Rails for our application's logic and also have the benefits of some kind of asynchronous event handling with publishing and subscribing when we need that. To achieve this, we will use Private Pub Gem which is built on top of Faye and makes it dead simple to publish and subscribe to real-time events in a Rails app.

Check out The Demo to have a feel of what we will be creating. Create an account on one separate browser window and on another log in using the default user provided on the login page then try simulating a conversation between yourself and the "chatty bot".

Getting started

We’re going to add the Instant Messaging feature to an existing Rails application. Below is a screenshot from a simple rails app (chatty) that uses Devise to authenticate users. It's current functionality is very basic. On the home page, we are just looping the list of all users except the currently logged in user.

We want to enable the users of our app to chat with each other. Let's start by modeling up the logic of our chat application. Our logic is very simple. A user will have many conversations and a conversation will have many messages. Here is the relationship diagram

Conversation Model

Let's get started by creating the conversation model. A conversation will hold the sender_id and the recipient_id both of which are instances of a user. The sender_id will hold the id of the user starting the conversation and the recipient_id will hold the id of the other user. On your terminal

$ rails g model Conversation sender_id:integer recipient_id:integer

It's a good idea to add an index to both sender_id and recipient_id as we will use this fields while searching.

Loading Gist

After migrating the database, lets update our user model. Since we don't have the user_id column in our conversation table, we must explicitly tell rails which foreign key to use.

Loading Gist

Next, lets edit our conversation model. A conversation will belong to both a sender and a recipient all of which are instances of a user.

Loading Gist

As you can see, our conversation will have many messages. We are then validating uniqueness of the sender_id and passing a scope of the recipeint_id. What this does is that it ensures that the sender_id and the recipient_id are always unique so that we only have unique conversations in our application. For instance, a conversation with (sender_id: 1, recipient_id: 2) and another with (sender_id: 2, and recipient_id: 1) should never occur since the conversation is essentially between the same users.

We have also added two scopes involving and between. The first scope will help us retrieve all conversations of the currently logged-in user while the last scope will help us check if a conversation exists between any given two users before we create the conversation.

Message Model

Now that we have our conversation model, lets proceed and create our message model. Run the following command on your terminal and run rake db:migrate.

$ rails g model Message body:text conversation:references user:references

Our messages table will have a body, conversation_id, and user_id columns. The conversation_id column will keep track of which conversation a message belongs to and the user_id column will keep track of the user who sent the message during chat. Adding some validations

Loading Gist

Logic Flow

Now that our models are in place, I want to explain the general flow of how the inline chat application will work. On our home page, we will add a send message button along each user's name. The button will hold two data attributes i.e. the id of the current user and another id of the reciever id. When a user clicks the button, we will send an asynchronous request to our rails app with the current user's id and the recipient id. If a conversation exists, we return the conversation id immediately, otherwise we create the conversation and return the id of the newly created conversation.

We will then pick, the conversation_id returned by the server using jQuery. Using this conversation_id, we will then request the respective show page of that conversation which will have a list of all its associated messages. For instance, if the server returns conversation_id 3, we will request the html page at conversations/3. We will then append this conversation data in our home page in a popup div.

Adding the message button

For each user we are displaying on our home page, we associate a send message button with him or her. The data-sid attribute will hold our current users' id while data-rip attribute will hold the recipient's id. We will send this values through an ajax request to our server which should create a conversation if necessary.

index.html.erb

Loading Gist

To keep this tutorial, short I have created most of the jQuery logic in a single file which I will link here. I have tried to make it as modular as possible and also provide comments on each method so it shouldn't be hard to comprehend what's cooking. Lets create a file chat.js inside our javascripts folder and paste the contents of chat.js. This file has all the functions we will need when creating chatboxes in our home page and also communicating with our rails app.

Let's not forget to add this file to our javascript manifest file.

If using rails 4 and turbolinks, require this file before requiring turbolinks.
//= require chat

In my users.js we'll listen for various events on our home page document and call respective methods inside our chat.js file

users.js

Loading Gist

Creating Controllers

We now have our javascript files logic ready all is left is piecing up our conversations and messages controllers to handle requests from our javascript file. Let's start by our conversations controller

$ rails g controller conversations

Our conversations controller will have only to actions, the create and the show actions.

conversations_controller.rb

Loading Gist

You will notice, the layout false directive. This is because we don't want the show view inheriting from application.html layout. We will be appending this view on our home page.

In the create action, we start off by searching if a conversation exists between the sender_id and recipient_id. Recall our between scope we defined earlier in our conversation model. If a conversation is found, we return it and assign it to the @conversation instance variable. If no conversation was found between the two users, we create a new conversation. We then eventually return a json response with the id of the conversation.

Our show action is also pretty standard, after getting the conversation with the specific id, (note this id is sent by our javascript code in chat.js), we also find who is receiving the message. We will use the receiver's name as the chatbox title in our chat.

Installing private_pub

It would be nice if we installed private_pub at this point as our next set of task, we will be utilizing functionality offered by the gem. Add private_pub gem in your Gemfile and run bundle. Installing it will also install Faye and its dependencies. We will also include the thin gem as we will be using it to serve Faye.

gem 'private_pub'
gem 'thin'

Next up, we need to run the generator provided by private_pub to generate the configuration file and a Rackup file for starting the Faye server.

rails g private_pub:install

We can now start up that Rack server by running this command on a separate terminal

rackup private_pub.ru -s thin -E production

This command starts up Faye using the Thin server in the production environment which is necessary to get Faye working. The last step is to add private_pub to the application’s JavaScript manifest file.

//= require private_pub

With private_pub installed, we can now proceed to make our first view that uses private_pubs functionality. This will be the show view of our conversation's controller

show.html.erb

Loading Gist

What stand's out here is the suscribe_to method. Here we subscribe to a channel ( the conversation's path ). We will use this same path to publish update notifications to this channel from our controller. We do this by calling subscribe_to and passing in the name of a channel which takes a format of a path. In our case we pass the current conversation's path.

The suscribe_to function is provided by the private_pub javascript we required inside our application.js manifest file. We also notice that our form will always be submitting via ajax due to the remote option.

Our last controller is the messages controller.

$ rails g controller messages

messages_controller.rb

Loading Gist

We only have the create action for the messages controller. We store the conversation's path in the @path instance variable. We will use this path to publish push notifications to our view. Remember we suscribed to the same url in our conversation's show view. This will always be unique for any two users in our app.

Our create action will render a javascript template. Let's go ahead and create that. In our messages folder create this file

create.js.erb

Loading Gist

Here we publish to the same path we suscribed to in our view. We also asign a number to variables from our rails app to variables in our javascript file. You are probably wondering what the following line does?

var reciever_id = $('meta[name=user-id]').attr("content");

We need a way to identity who is the recipient when publishing the notifications. A simple way around this is to create a meta tag in our application.html layout file that store's the id of the currently logged in user. In the head section of our layout file add

Loading Gist

You will also note that we are rendering a message partial. We have not created that yet. In our messages folder

_message.html.erb

Loading Gist

Note, we have used to helper methods self_or_other and message_interlocutor. They both take a message as an argument. Lets go ahead and define them. In our messages_helper file

messages_helper.rb

Loading Gist

Since we created our conversation's controller and messages controller, we have not yet defined their respective routes. Let's add them right away

routes.rb

Loading Gist

Notice we don't have yet any stylings for our chat box. Create a file chat.css in our stylesheets folder and paste the contents of chat.css. Let's also add the fon't awesome css in our application.html layout. This will provide us with some nice icon stylings for the minimize and close buttons.

application.html.erb

Loading Gist

Testing our chat app

Here comes the most interesting part of the tutorial. Our application should now be capable of handling near-realtime instant messages between any two users. In one browser window, I'm logged in as "Joseph" and in another i'm logged in as "Kevin". As "Joseph", clicking on Kevin's send message button, creates a new conversation between us and pops up a beautiful chat window. On my other browser as "Kevin" clicking on Joseph's send message button pops up a similar window and we can now chat instantly!. Check it out

And that's it for this tutorial. Hope this gives you an overview on how to go about implementing an instant message type chat for your rails application. Have any questions and or comments? Feel free to use the comments section below. Something not working out? feel free to also clone this application on my Github repo and compare.

Happy Hacking!

Update 12/04/2015

For those of you looking to setup your own instance of FAYE server on Heroku, take a look at an example FAYE app


108 Comments

___

Thomas Quiroga

06 Aug 14

Huge thanks, it's really a good work!

santhu46

11 Aug 14

Hey wonderful tutorial works fine. I need to develop Same functionality for mobile (IOS and andriod chat using back end as a rails ) rather than web, Please help if u have any idea. Helpful..

kumrzz

20 Aug 14

love it, nice to see a relevant and recent app on privatepub: thanks! I was tearing my hair out failing to get such an app out ... one suggestion though, I think its best to have more than one user setup in seeds.rb coz otherwise when u start out u can't start chatting(and its not straightforward creating one using the base CRUD on the app) Also think it'll be nice to add basic setup instrns such as bundle install and so on. ... happy to enter a pull etc.

lawrenceN

04 Sep 14

This is a nice idea man and very clear writing.

ashishgoojar

23 Sep 14

Hi JOSEPH. Great job done. really ice tutorial. I tried to use the codes in my app and it was working in local machine. But i am unable to make it work once deployed on Heroku. Nothing happens once I click on "Send Message". Any help??

abdugaliyev

07 Oct 14

Hi man! thank you for this greate tutorial, but a have one question, its works only in root_path but if i need this work all on app pages? how i can do this? thanks again

tedma4

10 Oct 14

I loved the tutorial. I'm trying to use it in my app. How would you place a user's image in using paperclip?

Vitor Torres

14 Oct 14

I've created conversations controller and show view for this controller but ajax calls still returns : POST http://localhost:3000/conve... 500 (Internal Server Error)

Anthony Liang

28 Oct 14

Thanks for this awesome tutorial, Joseph! One thing I've been trying to figure out is that currently if one user messages another user, that user isn't alerted to the message unless they open up the window. How could you alert the recipient of the message by popping up the chat window like in GChat?

Mahmoud Coudsi

10 Nov 14

This is really really amazing! I just ran through the steps and it works perfectly on my computer. However, when I try to use it using Safari on my Iphone, the message is sent to my computer and the chat window is update but the chat window on Iphone is not updated, I have to reload the page for the new message to show on iphone. Any idea why could that be? thanks!

Ivan Petrov

19 Nov 14

Amazing guide! Thanks! In chat.js I think it is better to wrap all code after ajax method in `done` callback.

jensitus

01 Dec 14

Hi Ivan, try in config/private_pub.yml in development: instead of server: "localhost:3000" server: "192.168.1.:3000

Ryan Decker

04 Dec 14

Hey, guys... I'm having a bit of trouble positioning the chatbox in my app. I have a footer, and whenever I open the box, it goes below the footer and also creates another footer. So...what do I do? :D And one more thing...has anyone figured out the way to make the chatbox stay after reload? Thanks.

Chandrabhushan Yerabatti

10 Dec 14

Thank You Michael Teshome Dinku......I put this PrivatePub.publish_to("/conversations/#{@conversation}/new", "alert('#{@message.body}');") in message_contoller creation action but it doesn't work for me. When I reload the page then only I'm receiving messages.I'm struggling in this .Any help? Thanks.

Keith Hunniford

10 Dec 14

This is awesome work Joseph! Semi related.. I've been looking at Faye / Heroku mix too and then I found Pubnub.com. Have you ever played with Pubnub? Considering using that for something similar to what you've done.

Yamini Shaik

26 Dec 14

Hi Joseph!I’m new to ruby on rails. Its fantastic tutorial. It works only on root level.I need to implement same chat app for my project using angularjs and rails.I'm unable to return the json format for conversation controller and messages controller. Can you please help on this.And I unable to understand how the routes are working in this app at root level.Would you please explain me on this. Thanks

Rakesh Varma

29 Dec 14

Is it work with Rails4 with MongoID?

Ahmed Reza

08 Jan 15

it worked for me but nothing happen when i click on the send message button....it gives a # in the url...am very new with rails but wanna learn this tutorial plz help...

Ahmed Reza

09 Jan 15

Hey Joseph...tnx a lot buddy but i waana use this on a different app....like my problrm is i have everything working gr8 but i jst wanna know wht link to use in rgis section of ur lovely tutorial... current_user.id, "data-rip" => user.id %> how to change that # and by what in the link to send message line....plz buddy plz help na plz

Ahmed Reza

10 Jan 15

its showing the following error `couldn't find file 'private_pub'

Yamini Shaik

24 Jan 15

Hi Joseph....Its a fantastic tutorial for chat app.Is it work with mongoid and rails4?

David Chriqui

17 Feb 15

Thanks for this great tuto :) A little improvement from chat.js instead of doing a get request to relative url here : $.get("conversations/" + conversation_id, function (data) { $('#chatbox_' + conversation_id).html(data); $("#chatbox_" + conversation_id + " .chatboxcontent").scrollTop($("#chatbox_" + conversation_id + " .chatboxcontent")[0].scrollHeight); }, "html"); add a "/" just before the conversations resources in order to be able to access this resources even if you are manipulating your users resources through the view.

norman santiago

17 Feb 15

Thanks for the great tutorial. I just want to ask how to do this in group. I mean I have group which is called MyRoom and all of those who are in that room can only see the messages well of course you have a uesr more than 2.

Ahmad Hasan Khan

24 Feb 15

Hey It's very helpful, Thanks very much, anyone knows how to show online users ?

Jeová Guilherme de Carvalho Filho

05 Mar 15

Help me, I got the error, Error: Syntax error, unrecognized expression: #chatbox_ [object Object] anyone seen this?

suresh kumar v

10 Mar 15

Thanks for this awesome tutorial, Joseph! I'm trying to add support for anonymous user chat.so some advice would be appreciated.

Joe Nilan

11 Mar 15

This is really awesome. thanks for the tutorial. My only problem is getting it work on another page. Instead of the send message button using /conversations/# it uses /jobs/conversations/# and gives me a routing error ActionController::RoutingError (No route matches [POST] "/jobs/conversations/2"): when i'm assuming it should just be /conversations/2 Jobs is another area of my website. I'm assuming the problem for me is in the $.post("/conversations", { sender_id: sender_id, recipient_id: recipient_id }, function (data) { chatBox.chatWith(data.conversation_id); line in the users.js file and it's using the directory above it as it's base what do i need to do to get it to route correctly any help is MUCH appreciated.

malav desai

25 May 18

That's very helpfull article for me.. And Its working perfect on localhost. My app is deployed on Digital Ocean + Nginx. How can i Make Faye/Thin Config on Digital Ocean So that It will work in real Time? Thanks...

Complitech Cspl

17 Mar 15

Hey Joseph,nice tutorial. I have integrated this feature in my app and it is working fine.I want to notify user when message arrives.Right now,if chat box open only than it will shows conversation.So,is it possible to notify receiver when message send by sender?

pranav prashant

20 Mar 15

I deployed your app on heroku, but found that it works only on http but not over https. Is there a fix. Was thinking of adding facebook and google+ login

Tom Goldenberg

19 Feb 15

I implemented all of the provided code, but the "message" buttons do nothing when clicked. If the a href leads to "#", I don't see how to get it to work, and am not familiar with JQuery. Any suggestions? Thanks!

Nico Vancamp

24 Mar 15

Could someone help me on how to count the number of unread messages and display that in the your conversations list?

Honza Vosmik

28 Mar 15

Great tutorial and really helpful to me! One question. How would you make to have the chat window in same state as it was when you refresh a page? For example, if one window is opened, another minimized, you refresh the page and it's still the same. Thank you once again! :)

Aditya Majeti

09 Apr 15

HI, JOSEPH NDUNGU i have a problem on calling " /conversations" controller in user.js its is routs to index of conversations controller which is not defined. but i changed to /conversations/create and i just create conversations/create.html.erb but it is showing 404 i dont know why popup of message box is not opened

Aulia Sabril

26 Mar 15

Thanks; great tutorial, Joseph if you don't mind, how can we add video or talk with microphone in this chat??

Vaibhav Kale

08 Apr 15

great tutorial Joseph. Thank you.I am facing some issue here. Once I have setup the entire code based on what is given here nothing seems to be happening on clicking the send message link. I am getting the below mentioned error which i copied from the console. Any suggestion would be of great help. Thanks send jQuery.extend.ajax jQuery.(anonymous function) chatBox.createChatBox chatBox.chatWith (anonymous function) fire self.fireWith done callback

Aditya Majeti

09 Apr 15

HI, JOSEPH NDUNGU i have a problem on calling " /conversations" controller in user.js its is routs to index of conversations controller which is not defined. but i changed to /conversations/create and i just create conversations/create.html.erb but it is showing 404 i dont know why popup of message box is not opened

Ben Forrest

11 Apr 15

So useful! Nice one I wondered if anyone managed to get offline caching of messages working eg gmail chat when the recipient is offline it message is stored until they login

David Chriqui

12 Apr 15

Hi Joseph, Thank you very much for your very useful blog tutorials. I've successfully implemented your gmail like chat into my app but I encounter some troubles setting up faye in a production environment with heroku. I've used this project to get private_pub Faye running on heroku : github.com/iamnan/heroku_private_pub This is not working with my project as well as your chat app. Would it be possible to get the code (through github) you've deployed to heroku in order to get running the Faye server you use ? Thank you

Mubashwer Salman Khurshid

14 Apr 15

Hi.. i got it working but the messages do not appear real-time.. i have to refresh the whole page.. and there are no error messages in the console log so I don't know what im doing wrong

Андрій Пугач

01 May 15

do we need UserController, i followed this guide but now am getting error uninitialized constant UsersController

pvijayror

09 May 15

Thank you working fine... but not 100% useful. Only problem: "if one user messages another user, that user isn't alerted to the message unless they open up the window. How could you alert the recipient of the message by popping up the chat window like in GChat?"

m-sakthivel

21 May 15

Hi I tried this out, I have a problem here when i post a message am getting template missing error since we are using create.js.erb but it's looking for html file i don know hw to fix this any one can help me pls.....

Anna

21 May 15

Hello! I’m also having the same problem as MUBASHWER SALMAN KHURSHID (the chat does not update in real-time, but the sent messages of both parties exist when I refresh the whole webpage). I cloned JOSEPH NDUNGU’s exact app from Github, but it has the same issue as described above. Clues?

Anna

21 May 15

Otherwise, the url in private_pub does not work. Is this not correct (obviously not, since it’s not working for me, but what else should go there): server: "http://localhost:9292/faye/...”?

sarahgupta022

10 Jul 15

Hi Joseph, Thank you very much for your very useful blog tutorials.I am trying to put "gmail like chat" in my existing code. but i receive error in my web page: Unknown action(The action 'index' could not be found for ConversationsController) from my Conversations Controller.rb . i try to put def index but after that i get another error: Template is missing Missing template conversations/index, application/index with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "C:/Users/Arvind/project/book/app/views" * "c:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/twitter-bootstrap-rails-3.2.0/app/views" * "c:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/devise-3.5.1/app/views" Now i really stuck in my app and i don't know how to get over with it. can u plz plz help me. My git repository at: https://github.com/sarahgup...

Akshay Gupta

11 Jul 15

Audio was also not getting automatically played. So download any notification sound on internet and put it in public directory naming notify.mp3 and it will start working

pvijayror

18 Jul 15

Hi Akshay Gupta, Please let me know can you describe to me automatically opening the chat window

Sanjeev Kumar Mishra

05 Jun 15

Hi Joseph, this is by far one of the most useful tutorials I have ever found in the recent past :) thank you so much for this. BTW, I am also one of those who is looking for the following 2 things: #1. Open the chat window of the other person if he's online automatically: If I had been in conversation with another user already and had just closed it for some reason, the chat window does popup for me if that same user sends me another message. But nothing happens if someone has just initiated a conversation. Would be great help to get this one in... I know a lot of people have already requested for it, so I hope you help us around this. Or just gimme some idea/hint :) #2. Detecting if a user if online of offline and based on that showing some visual on the chat window / hide the send message button etc

pvijayror

10 Jun 15

Hi Joseph, Thank you for update :) Plase fix ASAP automatically opening the chat window

Anil Singh

23 Jun 15

Hi Joseph, Thanks for this nice tutorial, I am facing one issue with it. Started GET "/faye.js" for 127.0.0.1 at 2015-06-23 15:27:12 +0530 ActionController::RoutingError (No route matches [GET] "/faye.js"): Could you please help to fix this issue. Thanks in Advance :)

Anil Singh

23 Jun 15

I have fixed this issue.

Akshay Gupta

11 Jul 15

I have posted my solution on above thread...for opening the chat box automatically for another online user

moussasarr

20 Aug 15

Great tutorial. Now I am wondering if you can from here have a inbox, trash and sent that will look like the one you made with mailboxer but using only private pub and thin. Can you go from here to an inbox system in coordination with the chat messages ? If so, how ?

Weijie Gao

27 Aug 15

hey! I wrote a short blog post on how to set up the private pub messenger for https/ssl. There was a mistake in the private pub read me for this issue. check it out! http://www.weijieworld.com/...

Teki.V.Sivaramakrishna

14 Sep 15

It took me two days to understand the process of faye push server and after following AKSHAY GUPTA's reply .... now I can successfully alert the other user when someone initiates the conversation. Pretty thanks to akshay and joseph ndungu.

Akshay Gupta

14 Sep 15

Thanks Teki.. good it was helpful...

Bruno Siqueira

27 Sep 15

Hey, Joseph! Thank you for the great tutorial! private_pub had been outdated for more than 3 years. Do you know if there another gem option? Thanks?

xbits

23 Sep 15

Had a problem which took me a while to figure out. Faye channels were not being subscribed due to GET parameters in the channel name EX: "/conversation/3?locale=pt". Faye would then send a response with error 405 invalid channel. In case anyone has the same problem simply add ```ruby your_channel_name.split('?').first ```

Szilard Magyar

05 Oct 15

Hey! Awesome tut! I am pretty new to rails. Could sby tell me how I could embed the chat function into rails? So when I click on a user show page the chat is already there as part of the rails app, without using any JS to open the chat window.

bangoc123

24 Oct 15

How can i display this chat at any page in my app? Please!!!

lmahendra

05 Oct 15

Hi Joseph, thanks for an awesome tutorial. I could make it work on my localhost successfully. However, when I deployed it to my dev server running nginx on AWS having linux AMI, I had to reload the page to see new messages. I added server IP in private_pub.yml and updated nginx.conf with /faye url, also opened 9292 port from aws console. but not able to resolve the following error Errno::ETIMEDOUT in Spree::Messages#create Showing app/views/spree/messages/create.js.erb where line #1 raised: Connection timed out - connect(2) for "54.xx.xx.171" port 9292

lmahendra

05 Oct 15

adding //= require private_pub to application.js resolved my issue, god, how did I missed that? Now I want to add API functionality to the chat for building android / ios application. If anyone already did that, please guide me.

maxmeira

29 Oct 15

Excellent tutorial dear Joseph! Need to put the button "Send Message" on views users / profile and so he opens the message box for that particular user, please guide me how to do this! Be with a description or sample, is of paramount importance! Congratulations for the work, very grateful!

zelLimbo

29 Oct 15

Fantastic writing . I was fascinated by the info . Does anyone know if my company might be able to obtain a blank 2012 CDC CDC/NCHS-6205-1 version to type on ?

leongg

31 Oct 15

Hi Joseph, I got an error: Can't verify CSRF token authenticity ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken: [...] Have you seen that error? do you know how can I fix it? Many thanks!

rmatejacabello

28 Nov 15

For those who want to do an auto popup window when someone sends you a message, I just realized there is a commit request in the Github brung from the user Mubashwer that fixes that. Check the files changes here and include it in your code: https://github.com/Joseph-N... Basically this user created a channel right after loading your application that subscribes to a "notifications" channel. This is also very helpful to know when the user is online or offline since that channel is being subscribed when you enter the app. You can take a look at this discussion here from przbadu (https://github.com/ryanb/pr...) where he uses app.bind(:subscribe) and app.bind(:unsubscribe) events that fire up when the user subscribes to a channel. You can play with the code and detect every time an user subscribes to the notification channel which would be the same as knowing when the user comes online or offline. With this, I think this chat is 100% operative and useful for any application. (Would be awesome to have also the "Typing.." message)

Jan

01 Dec 15

Hello Joseph, I don't know if there was an update but at the moment I receive a 500 internal error when I try to send a message, as well as in your Demo > http://railschattyapp.herok.... Any tips? Thanxs .-)

Tom Caridi

16 Dec 15

Hey Joseph, first of all thanks for the super detailed tutorial! I implemented everything as you have but when clicking on the Send Message button next to the users, nothing happens. My code is exactly the same as yours so I'm wondering if it's a Ruby or Rails version issue since you built this a while ago. Any advice?

lmahendra

18 Dec 15

can you provide more details as in what's the error you are getting and RoR version?

pragatisigma

28 Dec 15

Hi Joseph, Amazing tutorial. But for a receiver to receive alert i used "/conversations/#{@conversati...}/new" and it is not working. Also, I want to popup remain open for all the pages even i refresh the page like facebook. Any help?

sireesh

06 Jan 16

HI joseph this is tutorial thank you. please solve my issue when ever click on send a message link at that time only the channel is subscribing .if user is not click on the button he is not got any message.

stephane cedroni

07 Jan 16

Anybody tried to add an index action on the conversations? I am trying to display the list of conversation like gmail. But can't find a way to efficiently fetch the interlocutors with a JOIN (otherwise this is doing N+1 query). Anybody found a solution for that?

Sebastian Velandia

11 Jan 16

Great tutorial, now how to add file attachments to the messages?

Sebastian Velandia

11 Jan 16

By the way, the demo app is not working!!

khavq

13 Jan 16

This is really nice tutorial, I was making it work on local (computer A) but when I using another computer (computer B) to access 10.1.0.125:8520 so I got a problem. When I type on B so A still can received the message but chat list on B is not update and when I type on A nothing happen. Any ideas can help me ? Thanks for your time.

Kevin Yeh

04 Mar 16

Danthes is a better better gem to use as private_pub is no longer maintained. https://github.com/dotpromo...

harshad26

08 Apr 16

I setup it but just open chatbox. Not received message to another person. Also when i write message and post but not show in chat window. Its show only after reload page. What i missed here. Any one have a idea. Thanks

TylerTaylor

15 Feb 16

The message pop up is not working for me, it's pointing to '/#' and at this point I have cloned and copied your code.

John Owuor

23 Feb 16

Mine works well, finally. \o/. But it only works in the index page of the app. I would like to have it work from another resource e.g localhost:3000/profiles/5/conversations/1 instead of localhost:3000/conversations/1 . Any Idea how to go about this?

John Owuor

25 Feb 16

figured it out. will make a pull request soon

harshad26

08 Apr 16

messages save into database but not show instant. Its show after reload window. Why? any one have.

kinyo

23 Apr 16

Please help i need to know which part of the code requires a user to be signed in in order to display the pop up message box, since i need to change it i am rendering the message box on a separate controller view i have already done this but i have multiple models for devise guest and user i need the user authentication removed i have removed the authenticate user from the message and conversations controllers already but the message box only displays if user is signed in

kinyo

23 Apr 16

oh managed to get it working

dsCloud

30 Apr 16

An amazing tutorial Joseph. Thanks a lot!!! However, while trying to run...rails g private_pub:install.... I encounter this error Could not find generator 'private_pub:install'. Maybe you meant 'devise:install', 'responders:install' or 'integration_test'. So i could not proceed, obviously. Any assistance/guide on what to do will be highly appreciate.

dsCloud

30 Apr 16

I am developing on Nitrous environment,

poombavai

01 Jun 16

Hey all.. I am a newbie to Rails. I want something similar to this. How do i implement Chat with us in my website. (Any one can ask queries to us or something like that through online). Suggestions please..

Subham Gupta

05 Jun 16

How can i add image option in message ?

ryanameier

22 Jun 16

Hey guys (and gals) for those that are getting issues when clicking "sending message" and your 100% sure everything is correct. Make sure to delete users.coffee and make sure you have the users.js file in the javascripts pipeline. users.coffee actually interferes with users.js halting the messages from loading in Rails4/rails 4 (weird right?). Vote up if this helped!

KhanradCoder

25 Jun 16

GREAT! tutorial by the way. I am new to rails and want to add instant messaging into my application. The problem is is that when I click "Send message" on a user, nothing happens. Any help would be greatly appreciated. Thanks!

Ranga Nayakulu Modi

28 Jun 16

Hi Joseph, Thanks for the tutorial. I'm having one issue: pls help me. ActionView::Template::Error (Failed to open TCP connection to localhost:9292 (Connection refused - connect(2) for "localhost" port 9292)): 1: 2: var id = ""; 3: var chatbox = $("#chatbox_" + id + " .chatboxcontent"); 4: var sender_id = ""; app/views/messages/create.js.erb:1:in `_app_views_messages_create_js_erb__978440772584947251_48744220' Pls help me.

C LOKESH REDDY

30 Jun 16

Hey Joseph, it was a great yet simple article. I completed popping up those conversation windows as well, just subscribed to conversations index path and triggering the respective users start chat method in users.js. Thanks again, this is a great article.

KhanradCoder

06 Jul 16

Great Tutorial, just one problem, POST http://localhost:3000/conve... 500 (Internal Server Error) Gets called in my console when I run locally.

bibekdas

20 Jul 16

Hello Joseph, recently I implemented your chatty in one of my projects. In your "chat.js" file in line no. 99, you have the line "$.get("conversations/" + conversation_id, function (data) {". This created a huge issue as it did not open the chat box when i clicked on the send message link. After going through the code thoroughly, I found that the get method calls the conversations controller but the path does not start with the root. So when I added a "/" just before the "conversation", it worked fine. I think this small thing can create a huge issue. The changed line is "$.get("/conversations/" + conversation_id, function (data) {". I still have a doubt why you used the meta tag in the layout as it threw rails exception to me. When I removed it , everything was fine. I am working with rails 4.2.6. If you could explain, it would be better. Thank you :)

nish4114

22 Jul 16

this is amazing . but i have been stuck on one thing .. i have two user models Individual and Company , anyone can chat with anyone in this case how can i achieve this ?

Niels Siskens

06 Aug 16

Hey Guys, Anyone else having the issue that if you close the chat that then all the messages appear on the left side? When I am chatting, all is normal, but when I close the application and come back later...all the messages both from the friend and myself are on the left. So it seems like they are being reset. Looking for a fix, any help is welcome!

Chris Kroon

18 Aug 16

Hey this tutorial is great! How do I make a window where I can see all the conversations and how can I show the target user that someone send him/her a message? Love this tutorial!

vampiricbeef

02 Sep 16

This tutorial really came in help!! I made a dropdown for my index!! Im having an issue listing the conversations!! for some reason only the sender can view the current_user.conversations.each. The recipient knows that a conversation exists but no data is returned. I noticed when i added a

Soumit

12 Oct 16

Chat messages are not Updating till i refresh the page on Staging server but it is working locally Below error getting in Server log ActionView::Template::Error (execution expired): 1: 2: var id = ""; 3: var chatbox = $("#chatbox_" + id + " .chatboxcontent"); 4: var sender_id = ""; app/views/messages/create.js.erb:1:in `_app_views_messages_create_js_erb___280632794399059979_59909120' app/controllers/messages_controller.rb:13:in `create'

komalwce

17 Oct 16

When I click on Send Message button I get nothing , it is going to users# but chatbox isn't coming

kiennguyen93

17 Oct 16

I also have the same problem when I clicked on the "Send Message" button, nothing appears

Clay Cribbs

24 Nov 16

Great Tutorial! https://github.com/ClayCrib... I created a barebones Rails project that includes devise, a basic animated login screen, bootstrap navbar, and this live messaging system. Anyone is welcome to use it! Thanks again for a great tutorial

Arunjpillai

29 May 17

Dear Joseph A creep has copied the same article and has published as his own in LinkedIn https://www.linkedin.com/pu... .Please do the needful Thank you

Sanjeev Kumar Mishra

29 May 17

I did the needful for that creep @arjun .... shame on people who call themselves engineers and do this kinda stuff man !!

Fernando Aureliano

09 Jul 17

Your demo project is hosted on heroku?

Eldon Loblein

18 Jul 17

Hi Joseph. Thanks for the tutorial! I've implemented it on a rails app with user profile pages. It seems to work great from my profile page. However, if I visit another user's profile, and then try to click 'message', for some reason it hits the user#show controller action, and refreshes the page, without ever hitting the messaging loop. Refreshing the same page allows the messenger to function properly again. Any idea what would cause this?

john-lanticse

01 Sep 17

Anyone have a working demo of this? Thanks

kkuivenhoven

25 Nov 17

I can't get my chat box to stay scrolled to the bottom upon a new message being sent. Any fixes for this? I've tried adding z-index:9999 to CSS for chatbox, messing with chat.js and users.js, etc. No luck

Latest Tutorials

___

How to download a file using Capybara and Poltergeist - Ruby New

In one of my recent projects, I was working on a scraper that needed to login into a website and download a file which I would then save to use later on. ...

Private Inbox System in Rails with Mailboxer

Introduction It's been quite a while since my last tutorial and since then I've recieved alot of requests by email to implement a private messaging system ...

Ajax Sortable Lists Rails 4

With me, is a simple to-do list application where users can create dummy to-do lists and displays them in card-like form just like in Trello. We want to e...

Managing ENV variables in Rails

Often when developing Rails applications, you will find a need to setup a couple of environment variables to store secure information such as passwords, a...

Gmail Like Chat Application in Ruby on Rails

Introduction We are all fond of the Gmail and Facebook inline chat modules. About a week ago, I came across a tutorial on how to replicate hangouts chat...

Load more scroll top