2

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?

1

1 Answer 1

10

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it fixed the problem for me.
I also needed to do Rails.start() in Rails 7 but this worked for me. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.