Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 6: Rails not defined [duplicate]

I am trying to fire a form submit using UJS:

  <%= f.file_field :profile_image,
                   direct_upload: true,
                   accept: 'image/png,image/gif,image/jpeg',
                   onchange: "Rails.fire(this.form, 'submit')"
  %>

However, I see the following error in the JS console:

ReferenceError: Can't find variable: Rails

The application layout file points to the application JS pack:

<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

And I can see that it loads by the output of console log:

console.log('Application pack loaded')
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("@rails/activestorage").start()

From what I understand, rails ujs should expose the Rails object. Is that right?

Why isn't the Rails variable available to the browser? What do I need to do to ensure it is?

like image 663
user3574603 Avatar asked Jan 28 '26 01:01

user3574603


1 Answers

I have learnt from this issue raised against Rails 6.0rc1 that I need to expose the Rails object myself. I wrongly assumed that it would work out of the box. Perhaps it did when Rails used the asset pipeline.

I am able to access the Rails object by adding this to my pack:

import Rails from "@rails/ujs";
window.Rails = Rails;
like image 135
user3574603 Avatar answered Jan 29 '26 18:01

user3574603