質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Action Cable

Action Cableは、WebSocketをRailsに組み込む機能。Rails4でオプションとして存在していたWebSocketをRails5で標準機能したものです。Railsアプリケーションと同様のスタイルで、Rubyを用いたリアルタイム機能を記述できます。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

WebSocket

WebSocketとは双方向・全二重コミュニケーションのためのAPIでありプロトコルのことを指します。WebSocketはHTML5に密接に結びついており、多くのウェブブラウザの最新版に導入されています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

0回答

702閲覧

リアルタイムチャットで受信した際の通知機能について

tatsuhiros

総合スコア0

Action Cable

Action Cableは、WebSocketをRailsに組み込む機能。Rails4でオプションとして存在していたWebSocketをRails5で標準機能したものです。Railsアプリケーションと同様のスタイルで、Rubyを用いたリアルタイム機能を記述できます。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

WebSocket

WebSocketとは双方向・全二重コミュニケーションのためのAPIでありプロトコルのことを指します。WebSocketはHTML5に密接に結びついており、多くのウェブブラウザの最新版に導入されています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2021/02/07 13:45

編集2021/02/07 15:17

Ruby on Rails でAction Cableを用いたリアルタイムチャットアプリを作成しています。
リアルタイムチャットでメッセージを受信したユーザに通知を送る機能を実装したいと考えているのですが、方法が思いつきません。

もし分かる方がいれば、お力をお借りしたいです。

ずっと困っているので、助けていただければ本当に助かります!
どうか宜しくお願いいたします。

以下のようなコードとなっております。

ruby

1class RoomChannel < ApplicationCable::Channel 2 def subscribed 3 stream_from "room_channel_#{params['room']}" 4 end 5 6 def unsubscribed 7 # Any cleanup needed when channel is unsubscribed 8 end 9 10 def speak(data) 11 # jsで実行されたspeakのmessageを受け取り、room_channelのreceivedにブロードキャストする 12 Message.create! content: data['message'], user_id: current_user.id, room_id: params['room'] 13 end 14end 15

ruby

1class MessageBroadcastJob < ApplicationJob 2 queue_as :default 3 4 def perform(message) 5 ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message) 6 end 7 8 private 9 10 def render_message(message) 11 ApplicationController.render_with_signed_in_user(message.user, partial: 'messages/message', locals: { message: message }) 12 end 13end

Ruby

1module ApplicationCable 2 class Connection < ActionCable::Connection::Base 3 identified_by :current_user 4 5 def connect 6 reject_unauthorized_connection unless find_verified_user 7 end 8 9 private 10 11 def find_verified_user 12 self.current_user = env['warden'].user 13 end 14 end 15end

Ruby

1class Message < ApplicationRecord 2 validates :content, presence: true 3 after_create_commit { MessageBroadcastJob.perform_later self } 4 belongs_to :user 5 belongs_to :room 6 has_many :active_notifications, class_name: 'Notification', foreign_key: 'visitor_id', dependent: :destroy 7 has_many :passive_notifications, class_name: 'Notification', foreign_key: 'visited_id', dependent: :destroy 8end 9

Ruby

1class MessagesController < ApplicationController 2end 3

JavaScript

1import consumer from './consumer' 2 3// $(function() { ... }); で囲むことでレンダリング後に実行される 4// レンダリング前に実行されると $('#messages').data('room_id') が取得できない 5// turbolinks を使っている場合は $(document).on('turbolinks:load', function() { ... }); で囲う 6$(function() { 7 const chatChannel = consumer.subscriptions.create({ channel: 'RoomChannel', room: $('#messages').data('room_id') }, { 8 connected() { 9 // Called when the subscription is ready for use on the server 10 }, 11 12 disconnected() { 13 // Called when the subscription has been terminated by the server 14 }, 15 16 received: function(data) { 17 return $('#messages').append(data['message']); 18 }, 19 20 speak: function(message) { 21 return this.perform('speak', { 22 message: message 23 }); 24 } 25 }); 26 27 $(document).on('keypress', '[data-behavior~=room_speaker]', function(event) { 28 if (event.keyCode === 13) { 29 chatChannel.speak(event.target.value); 30 event.target.value = ''; 31 return event.preventDefault(); 32 } 33 }); 34 35 $(".button").on("click",function(){ 36 var message = $(".speaker_txt").val(); 37 chatChannel.speak(message); 38 $(".speaker_txt").val("") 39 }); 40}); 41

HTML

1<div class="chat-room-container"> 2<%= link_to rooms_path do%> 3 <i class="fas fa-arrow-left fa-2x" aria-hidden="true"></i> 4<% end %> 5<% if @user.image? %> 6 <%= link_to user_path(@user) do %> 7 <%= image_tag(@user.image.to_s, :class => "top-image")%> 8 <% end %> 9 <span class="name"><%= @user.name %></span> 10<% else %> 11 <%= link_to user_path(@user) do %> 12 <%= image_tag("default.png", :class => "top-image")%> 13 <% end %> 14 <span class="name"><%= @user.name %></span> 15<% end %> 16<hr> 17<div class= "messages" id ='messages' data-room_id="<%= @room.id %>"> 18 <%= render @messages %> 19</div> 20</div> 21<div class= "message-form row"> 22<div class = "send-form offset-1 col-9"> 23<form> 24 <input class="speaker_txt col-12" name="content" type="text" data-behavior="room_speaker", autofocus> 25</form> 26</div> 27<div class= "send-button col-1"> 28<button class="button btn btn-primary"><i class="fas fa-paper-plane"></i></button> 29</div> 30</div>

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

y_waiwai

2021/02/07 14:05

コードはテキストで提示しましょう その際には、質問を編集し、<code>ボタンを押し、出てくる’’’の枠の中にコードを貼り付けてください
tatsuhiros

2021/02/07 15:18

ご指摘ありがとうございます。変更しました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問