LoginSignup
10
8

More than 5 years have passed since last update.

【Rails】ajaxで用いるRJS(.js.erb)ファイルでインスタンス変数展開できるって話

Last updated at Posted at 2018-12-16

やりたいこと

非同期処理と言えばajaxですが、RJS(.js.erb)ファイル内でcontrollerから引き継いだインスタンス変数を展開したい。

やりかた

indexで@userを作っていると仮定。
formの条件によって@userにどのユーザーdataが入るか変わるみたいな・・・。

controller.rb
def index
  ・・・
  ・・・
  @user = User.find_by(〜〜〜〜)
end
index.js.erb
  var username = <% @user.name %>

これでusername@user.nameが格納。

いつ使うのか

こんな感じの使われ方するかも?

index.html.erb
<div id="description#{@user.id}">未実施</div>
index.js.erb
  var userid = <% @user.id %>
  $(`#description${userid}`).text("実施済み");

remote: trueのフォームを送ると、非同期的に「未実施」 → 「実施済み」になるみたいな。

原理は

テンプレートで使う.html.erbと同じ埋め込みRuby(ERB)なので、原理は同じという考え方でOKなはずです。

10
8
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
10
8