1

I'm following a Rails Tutorial | Building a Link Shortener with Rails 6 and ruby 2.xx to build the same app. However, I'm using rails 7.0.4 and ruby 3.0.0. My create.js.erb file does not work. And from a quick lookup on google, I discovered .js.erb has been removed from rails 7 and replaced with turbo_stream and hot stimulus.js.

How do I hook my code in create.js.erb which is embedded ruby in javascript into the new rails 7 say links_controller.js under javascript >> controller directory. since the latter is purely javascript.

create.js.erb:

var lookupCode = "<%#= @link.lookup_code %>";

var element = document.getElementById('short-link');
element.innerHTML = lookupCode;

I created this file under javascript >> controller directory: links_controller.js

import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  connect() {
    this.element.textContent = "I believe I should hook the content of create.js.erb here";
  }
}

Pls, any help will be greatly appreciated. I did a lot of research and googling before asking this question. And the only one that could have answered my question was closed:

Ruby on Rails 7 - Is there any way to implement js.erb files?

simper
  • 19
  • 9
  • Javascript views have not been removed from Rails 7, but there is a push towards turbo views. You can specify a js view in your controller and use `create.js.erb` just like before. You probably need to call your controller action via a remote (= Ajax) form to trigger the js response, otherwise you may get an "unknown format" error. In your form, you can use `turbo: false, remote: true`. – Jussi Hirvi Dec 06 '22 at 08:42

1 Answers1

-1

You need to convert them (.js.erb) to Turbo Stream responses (.turbo_stream.erb) instead, which is not just rename files. You need to do it the Hotwire way.

Ken Ratanachai S.
  • 3,307
  • 34
  • 43
  • No, you don't. `js.erb` files work just fine in Rails 7. Hotwire is not mandatory to use in Rails 7. – shanet Jun 15 '23 at 22:50