Aadhi
Aadhi

Reputation: 21

Issue with setting up actioncable

My project is set up as rails only API application, and flagged with no javascript. they have added active admin to it and made necessary changes to it making javascripts folder in assets as required by active admin. now i need to add actioncable functionality along with chat for it. for user side it is fine as we are using react front-end. but for admin i need to implement actioncable to push messages in real time to browser. how can i set it up. I have even tried with importmap-rails. ruby- 2.6.5 rails -6.0.6.1

my approach was I tried to create a chat_channel.js in app/assests/javascripts/channels and added following snipped and added a javascript_include_tag as module in required page-view from admin

import consumer from "./consumer"

consumer.subscriptions.create("ChatChannel", {
  connected() {
    console.log("Connected to the chat channel.");
  },

  disconnected() {
    console.log("Disconnected from the chat channel.");
  },

  received(data) {
    console.log("Received message:", data.message);
    // Handle the received message here
  }
});

my consumer.js file has

import { createConsumer } from "@rails/actioncable"

const consumer = createConsumer()

export default consumer

error i am facing when it is loaded load_messages:1 Uncaught TypeError: Failed to resolve module specifier "@rails/actioncable". Relative references must start with either "/", "./", or "../".

there is no package.json file at the starting, but as tried to do so with npm install and add actioncable. but none of them worked.

i got it i am unable to load modules properly. i tried npm i @rails/actioncable, or yarn add @rails/actioncable. those things didnt help. i tried with impotmaps-rails following this guide. as this has similarities with my case.this also ended with same error.

Upvotes: 2

Views: 503

Answers (2)

Hector Correa
Hector Correa

Reputation: 26680

I had the same issue and the problem was that my installation of Vite was busted (not sure how).

Running vite --version showed me the correct version of Vite but also an error:

npm ERR! code ELSPROBLEMS
npm ERR! invalid: [email protected] /Users/my-user/my-project/node_modules/vite

npm ERR! A complete log of this run can be found in: /Users/my-user/.npm/_logs/2024-06-25T19_16_40_112Z-debug-0.log

I deleted my local copy of Vite via rm -rf /Users/my-user/my-project/node_modules/vite, reinstalled via yarn install and now vite --version does not show any error and Rails loads the application successfully.

Upvotes: 0

fguillen
fguillen

Reputation: 38772

I add here the @Ponny comment as an answer:

Running

bin/importmap pin @rails/actioncable 

in the Rails home directory fixed the issue for me.

Upvotes: 1

Related Questions