Help us understand the problem. What is going on with this article?

Rails で JS を Webpacker 管理にしたら、 data-confirm が動かなくなった

More than 1 year has passed since last update.

JS と CSS を Webpacker 管理にしたら、
link_to, method: :delete, data: { confirm: 'Are you sure?' } が動かなくなった。

application.html.haml(diff)
-    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload'
-    = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
+    = javascript_pack_tag 'application'
+    = stylesheet_pack_tag 'application'

環境

  • Rails 5.1.4

原因

Ruby on Rails 5.1リリースノート | Rails ガイド

従来のRailsでは、data-remoteやdata-confirmについてはjQueryに依存し、その他の機能をUnobtrusive JavaScript(UJS: 控えめなJavaScript)に依存する形で機能を提供していました。Rails 5.1からはこれらの依存が解消され、UJSはvanilla JavaScript(=純粋なJavaScript)で書き直されました。このコードはAction View内部でrails-ujsとしてリリースされています。

Rails5.1 では、 data-remotedata-confirm は rails-ujs に依存している。
app/assets/javascripts/application.jsrails-ujs を読み込んでいるが、
application.html.hamlapp/assets/javascripts/application.js の読み込みを外したため。

解決策

※2017/12/05に修正しました

rails-ujs を yarn で入れて、読み込む。

yarn add rails-ujs
app/javascript/packs/application.js
import Rails from 'rails-ujs';
Rails.start();

これで、 javascript_include_tag は削除できる。

app/views/layouts/application.html.haml(diff)
     %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
     %title PomodoroRails
     = csrf_meta_tags
-    = javascript_include_tag 'application'
     = javascript_pack_tag 'application'
     = stylesheet_pack_tag 'application'
   %body
mokuo
表参道でWebエンジニアをやっています。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした