maasiii
@maasiii

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

chart.jsリダイレクト時に表示しない

解決したいこと

リダイレクトした際にもchart.jsのチャートを表示されるようにしたい。

発生している問題・エラー

チャートを表示するページに画面遷移したらチャートが表示されない。
リロードすると表示される。

環境
ruby.3.2.0
rails.7.0.4

該当するソースコード

views/users/show.html.erb
<div class="container mb-5 pt-5">
<%= Gon::Base.render_data %>
  <canvas id="myChart" width="80" height="30"></canvas>
</div>



<script>
  const ctx = document.getElementById('myChart');

  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['January', 'February', 'March'],
      datasets: [{
        label: 'Dtaset1',
        data: [gon.label_backdata,  -15, -60],
        backgroundColor: '#ffb6c1',
        borderWidth: 1
      },
      {
        label: 'Dtaset2',
        data: [gon.label_frontdata, 10, -10],
        backgroundColor: '#ffdead',
        borderWidth: 1
      },
      {
        label: 'Dtaset3',
        data: [gon.label_infradata, -18, 18],
        backgroundColor: '#ffffe0',
        borderWidth: 1
      }]
    },
    options: {
      plugins: {
            title: {
                display: true,
                text: 'Chart.js Bar Chart'
            }
        },
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
</script>

Gemfile

source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.1.2"
gem 'bootstrap', '~> 5.1'
gem 'sass-rails', '>= 6'
gem 'jquery-rails'
gem 'ruby-vips', '~> 2.1', '>= 2.1.4'
gem "image_processing", ">= 1.2"
gem 'pry-rails'
gem 'gon', '~> 6.4'


# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
gem "rails", "~> 7.0.4", ">= 7.0.4.3"

# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
gem "sprockets-rails"

# Use postgresql as the database for Active Record
gem "pg", "~> 1.1"

# Use the Puma web server [https://github.com/puma/puma]
gem "puma", "~> 5.0"

# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
gem "importmap-rails"

# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "turbo-rails"

# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails"

# Build JSON APIs with ease [https://github.com/rails/jbuilder]
gem "jbuilder"

# Use Redis adapter to run Action Cable in production
# gem "redis", "~> 4.0"

# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis]
# gem "kredis"

# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
gem "bcrypt", "~> 3.1.7"

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]

# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false

# Use Sass to process CSS
# gem "sassc-rails"

# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"

group :development, :test do
  # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
end

group :development do
  # Use console on exceptions pages [https://github.com/rails/web-console]
  gem "web-console"

  # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
  # gem "rack-mini-profiler"

  # Speed up commands on slow machines / big apps [https://github.com/rails/spring]
  # gem "spring"
end

group :test do
  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
  gem 'rspec-rails'
  gem 'factory_bot_rails'
  gem "capybara"
  gem "selenium-webdriver"
  gem "webdrivers"
  gem 'launchy'
  gem 'capybara-screenshot'
end

自分で試したこと

turbolinkが原因なのかと思い、部分的に無効にするような記述にしましたが、解決しませんでした。

<script data-turbolinks-eval="false">
  // JavaScriptコード
</script>

turboに関する知見が足りず困っている状況です。
知見のある方がいましたら、ご教授よろしくお願いいたします🙇‍♂️

0

1Answer

こちら少しだけ原因がわかり、、
importmapが関係ありそうだと思い、以下のように記述してみましたが、
次は、scriptが読み込まれなくなりました。。。

どこが間違えているのでしょうか??

importmap.rb
# Pin npm packages by running ./bin/importmap

pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"

pin "jquery", to: "https://code.jquery.com/jquery-3.6.0.min.js"
pin "bootstrap", to: "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
pin "chart.js", to: "https://cdn.jsdelivr.net/npm/chart.js"
pin_all_from "app/javascript/custom",      under: "custom"
application.js
https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import "custom/chart"
app/javascript/custom/chart.js
  const ctx = document.getElementById('userChart');

  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['January', 'February', 'March'],
      datasets: [{
        label: 'Dtaset1',
        data: [gon.label_backdata,  -15, -60],
        backgroundColor: '#ffb6c1',
        borderWidth: 1
      },
      {
        label: 'Dtaset2',
        data: [gon.label_frontdata, 10, -10],
        backgroundColor: '#ffdead',
        borderWidth: 1
      },
      {
        label: 'Dtaset3',
        data: [gon.label_infradata, -18, 18],
        backgroundColor: '#ffffe0',
        borderWidth: 1
      }]
    },
    options: {
      plugins: {
            title: {
                display: true,
                text: 'Chart.js Bar Chart'
            }
        },
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
views/layouts/application.html.erb
<head>
  <title>Myapp</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>

  <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
  <%= javascript_importmap_tags %>
</head>
views/users/show.html.erb
<div class="container mb-5 pt-5">
<%= Gon::Base.render_data %>
  <canvas id="userChart" width="80" height="30"></canvas>
</div>
0Like

Your answer might help someone💌