1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptにRailsの変数を持たせるには

Last updated at Posted at 2021-06-03
1 / 2

今回オリジナルアプリの作成で、Railsの変数をJavaScriptで使えないかと調べて実装できたのでここに記録。

結論から言うとgemを入れたら簡単に実装できた。

まず、使用するのはgonと言うgem

Gemfileにgem "gon"と記載

ターミナルにbundle install

その後application.heml.erbのhead内に<%= include_gon %>と書くことでgonを読み取れるように

次に使用したいcontrollerの変数をJavaScriptで使えるように

@movie = Movie.find(params[:id])
gon.movie = @movie

変数@moviegonを加える

あとはjsで変数を使えるように
今回はアラートを用いてアラートの内容に変数を用いたいため以下の記述

alert(`正解は[${gon.movie.phrase}]です`);
1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?