LoginSignup
0
1

More than 3 years have passed since last update.

【Rails】JavaScriptを特定のビューで読み込む方法

Posted at

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

Slim導入

実装

1.application.jsを編集

=を削除する。
こうする事で、assets/javascripts内のjavascriptファイルが自動で読み込まれなくなる。

application.js
//変更前
//= require_tree

//変更前
// require_tree

2.environmentsを編集

開発環境で反映させたい場合はdevelopment.rb
本番環境で反映させたい場合はproduction.rbを編集する。

development.rb
Rails.application.configure do
  # 個別で読み込みたいjavascriptファイルを設定
  config.assets.precompile += ['gmap.js']
  # coffeeスクリプトは拡張子を付けるとエラーが出るので注意!
  config.assets.precompile += ['jquery.jpostal']
end

3.ビューを編集

~.html.slim
/ このページで読み込みたいjavascriptファイルを設定
= javascript_include_tag 'gmap.js'
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1