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

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

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

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

DELETE

ファイルシステムからファイル、データベースからレコードを削除することまたはメモリ内のオブジェクトの割り当てを取り消すことをさします。もしくは、HTTPプロトコルのDELETEを指すこともあります。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

WebSocket

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

Ruby on Rails

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

Q&A

0回答

1494閲覧

Action Cableを用いてコメントの削除機能の実装がしたい。

hana_123

総合スコア3

Action Cable

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

DELETE

ファイルシステムからファイル、データベースからレコードを削除することまたはメモリ内のオブジェクトの割り当てを取り消すことをさします。もしくは、HTTPプロトコルのDELETEを指すこともあります。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

WebSocket

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

Ruby on Rails

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

0グッド

0クリップ

投稿2020/11/25 10:14

前提・実現したいこと

rails にてアプリケーション実装をしています。

コメントの投稿削除機能をAction cableを用いて実装中です。
現時点で、投稿はwebsocket通信でできている状態です。
削除機能もAction cableを使って行いたいのですが、うまくいきません参考にさせていただいたのが、
https://qiita.com/Hijiri-K/items/13a4e06233d39ef040eb
https://teratail.com/questions/280419
の記事になります。

以下のソースコードにて不要なところ、また足りないところ、修正点などあればご指摘いただきたいです。
また、console上でのエラーも現段階で出ていますので載せておきます。

よろしくお願いいたします。

発生している問題・エラーメッセージ

console

1delete_channel.js:4 Uncaught TypeError: _consumer__WEBPACK_IMPORTED_MODULE_1__.default.subscriptions.create(...) is not a function 2 at Module.<anonymous> (delete_channel.js:4) 3 at Module../app/javascript/channels/delete_channel.js (delete_channel.js:43) 4 at __webpack_require__ (bootstrap:19) 5 at webpackContext (channels sync _channel.js$:10) 6 at Array.forEach (<anonymous>) 7 at Object../app/javascript/channels/index.js (index.js:5) 8 at __webpack_require__ (bootstrap:19) 9 at Object.<anonymous> (application.js:9) 10 at Object../app/javascript/packs/application.js (application.js:23) 11 at __webpack_require__ (bootstrap:19) 12(anonymous) @ delete_channel.js:4 13./app/javascript/channels/delete_channel.js @ delete_channel.js:43 14__webpack_require__ @ bootstrap:19 15webpackContext @ channels sync _channel.js$:10 16./app/javascript/channels/index.js @ index.js:5 17__webpack_require__ @ bootstrap:19 18(anonymous) @ application.js:9 19./app/javascript/packs/application.js @ application.js:23 20__webpack_require__ @ bootstrap:19 21(anonymous) @ bootstrap:83 22(anonymous) @ bootstrap:83

該当のソースコード

comment表示にあたる部分

html

1 2 <div class="comments-all"> 3 <ul id="comments"> 4 <% if @comments.present? %> 5 <% @comments.reverse_each do |comment| %> 6 <div class="comment-context" id="<%comment.id%>"> 7 <li> 8 <% if comment.user.avatar.attached? %> 9 <%= image_tag(comment.user.avatar, class:"avatar-post", id:"avatar-post") %> 10 <% end %> 11 <%= link_to comment.user.name, user_path(comment.user.id) %> : <%= comment.text %></li> 12 <%=link_to(comment_path(comment.id), method: :delete) do%> 13 <button id="<%=comment.id%>" class="delete-btn">削除</button> 14 <% end %> 15 16 </div> 17 <% end %> 18 <% else %> 19 <div class="comment-do" id="comment-do"> 20 NO COMMENT YET 21 </div> 22 <% end %> 23 </ul> 24 </div> 25

delete.channel.rb

class DeleteChannel < ApplicationCable::Channel def subscribed stream_from "delete_channel" end def unsubscribed # Any cleanup needed when channel is unsubscribed end def delete ActionCable.server.broadcast 'delete_channel', id: data['id'] comment = Comment.find_by(id: data['id']) comment.destroy end end

delete.channel.js

import { removeData } from "jquery"; import consumer from "./consumer" consumer.subscriptions.create("DeleteChannel", { connected() { // Called when the subscription is ready for use on the server }, disconnected() { // Called when the subscription has been terminated by the server }, received(data) { // Called when there's incoming data on the websocket for this channel } }) (function() { ({ "delete": function(id) { return this.perform('delete', { id: id }); } }); $(document).on('click', '.delete-btn', function(event) { return App["delete"]["delete"](event.target.id); }); }).call(this); (function() { ({ received: function(data) { var id; id = "#" + data['id']; console.log(id); return $(id).remove(); } }); }).call(this);

comment_controller

def create @comment = Comment.new(comment_params) @user = @comment.user ActionCable.server.broadcast 'comment_channel', content: @comment, user: @user if @comment.save end def destroy if Comment.find(params[:id]).destroy ActionCable.server.broadcast 'delete_channel', id: data['id'] end end

ルーティングの設定を変えてみた結果の記述です。↓
(postにネストさせたところにdestroyアクションをおくと
ActiveRecord::RecordNotFound in CommentsController#destroy
のエラーが出てしまったため)

resources :posts do resources :comments, only: :create end resources :comments, only: :destroy mount ActionCable.server => '/cable' end

補足情報(FW/ツールのバージョンなど)

ruby '2.6.5'
gem 'rails', '~> 6.0.0'
webpacker.ymlの記述も関係あるかわからないのですが載せておきます。

default: &default source_path: app/javascript source_entry_path: packs public_root_path: public public_output_path: packs cache_path: tmp/cache/webpacker check_yarn_integrity: false webpack_compile_output: true # Additional paths webpack should lookup modules # ['app/assets', 'engine/foo/app/assets'] resolved_paths: [] # Reload manifest.json on all requests so we reload latest compiled packs cache_manifest: false # Extract and emit a css file extract_css: false static_assets_extensions: - .jpg - .jpeg - .png - .gif - .tiff - .ico - .svg - .eot - .otf - .ttf - .woff - .woff2 extensions: - .mjs - .js - .sass - .scss - .css - .module.sass - .module.scss - .module.css - .png - .svg - .gif - .jpeg - .jpg development: <<: *default compile: true # Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules check_yarn_integrity: true # Reference: https://webpack.js.org/configuration/dev-server/ dev_server: https: false host: localhost port: 3035 public: localhost:3035 hmr: false # Inline should be set to true if using HMR inline: true overlay: true compress: true disable_host_check: true use_local_ip: false quiet: false pretty: false headers: 'Access-Control-Allow-Origin': '*' watch_options: ignored: '**/node_modules/**' test: <<: *default compile: true # Compile test packs to a separate directory public_output_path: packs-test production: <<: *default # Production depends on precompilation of packs prior to booting for performance. compile: false # Extract and emit a css file extract_css: true # Cache manifest.json for performance cache_manifest: true

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

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

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

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問