Peter
Peter

Reputation: 729

Automatically invoke new message from database

I want to build a function into my system, which can send and receive a message from one user to another in the form of an invitation like a text-field with the message"Do you want to go shopping with me?" and two buttons under this message-window "Accepted", "Not accepted".

I can already save the invitation-message in the database. Here is where it will be saved in db/schema.rb under message:

 create_table "processings", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.integer  "shopping_process_id"
    t.integer  "shopping_list_id"
    t.boolean  "accepted"
    t.datetime "responded"
    t.string   "message"
    t.index ["shopping_list_id"], name: "index_processings_on_shopping_list_id", using: :btree
    t.index ["shopping_process_id"], name: "index_processings_on_shopping_process_id", using: :btree
  end

Now I ask me how can I build a function, which automatically invokes this message for the user, who should receive this message, immediately after the message is saved in the database. Do you have an idea how I can implement this?

Upvotes: 1

Views: 28

Answers (1)

Jeremy
Jeremy

Reputation: 745

What you are asking for is server initiated communication - you want the server to send the client a message. This is not how HTTP works. With HTTP you send a request to the server and the server responds. So your options are:

a) Write a JavaScript function that sends a request to your server every minute or every few seconds and runs async (not recommended)

or,

b) Use websockets to create a link between the server and users, thereby being able to send as well as receive communication.

With web sockets, which I have some experience with, there are many options for implementation. The way that I did it was using Rails 5 ActionCable, the 'puma' gem (puma makes your Rails server threaded, which ActionCable needs), and Redis. This is a pretty good link here on how to implement Rails ActionCable for a chat. It goes step by step, you just need to change it for your own needs. It does have a fatal flaw though, which I fixed.

This is my fix for the article's github repo above. In the above article messages get sent to all chatrooms because the author does not make each connection specific to one chatroom, and instead makes it specific to all chatrooms. The trick to ActionCable is making sure that each connection sends only the right information to each user. You don't want all users receiving an invitation, so you'll want to make connections based on user ids or some other unique identifier, and send out confirmations based on that as well.

Good luck!

Upvotes: 1

Related Questions