1

I'm currently trying Rails 6.0.0 which seems to have moved the default javascript folder from app/assets/javascript to app/javascript. The application.js file is now located in app/javascript/packs.

Now, I want to add JS file for each controller action. For example I have:

  • UsersController#index
  • UsersController#show
  • UsersController#edit

On some controller action I need to add some javascript:

  • app/javascript/user/index.js
  • app/javascript/user/show.js
  • app/javascript/user/edit.js
  • app/javascript/user/form.js (assume in form I need some js tweak)

Here is what I'm currently doing. In controller view:

<%= javascript_pack_tag 'user/index', 'data-turbolinks-track': 'reload' %>

However, in index.js I can't call libraries which has been required in application.js. For example in application.js:

require("bootstrap/dist/js/bootstrap")

In index.js I call bootstrap specific JS for popover, modal ... I got:

Uncaught TypeError: $(...).modal is not a function

I don't want to write all JS in application.js because every page have to load entire website JS which is nut! That why I want to split them and include when I need.

Beside, why we have to require JS file in application.js? If we using javascript_pack_tag do we need to require those file in application.js?

Here is a dummy repo I just created.

Ref: here explain how to require a custom JS file.

truongnm
  • 2,311
  • 2
  • 31
  • 48

2 Answers2

0

Add to your application.html.erb:

<%= javascript_pack_tag controller_name %> for controllers <br/>
<%= javascript_pack_tag action_name %> for actions
Rastalamm
  • 1,712
  • 3
  • 23
  • 32
jarpo
  • 1
0

You can create a folder structure as your view. So say you have some custom form validations you want to add inside the edit view of the user. You have the following structure: app/views/users/edit.html.erb

In your edit.html.erb, remove all your JS code and remove the script tags. Instead add:

<%= javascript_pack_tag('user/edit') %>

Open app/javascript/packs folder. Create the same folder structure as your edit view like this: app/javascript/packs/product/edit.js.

Inside edit.js

window.onload = function () {
  // Your custom form validation JS code for users/edit
}

Open config/application.rb, and inside the module:

config.assets.precompile += ['user/edit.js']
# Keep appending more assets as you wish.
Elias Glyptis
  • 470
  • 5
  • 9