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

Rails5のAjax

More than 1 year has passed since last update.

Rails Guideの説明を読んでもいまいちよくわからなかったので頭の整理をするために書いておく。

  1. form_with, link_to, buttonなどでAjaxリクエストを送信
  2. コントローラーの respond_toの中にformat.jsを書くと対応するxxxx.js.erbでJavascriptコードを作成する。
users_controller.rb
def index
  @users = User.all
  respond_to do |format|
    format.js
  end
end
  1. 返されたJavascriptによって元画面の書き換えが行われる。
index.js.erb
# 実際はappendToではなくreplaceWithを使って書き換えるケースが多いと思う。
$("<%= escape_javascript(render @users) %>").appendTo("#users");

ちなみに renders @users は 対応する部分テンプレート(_user.html.erb)に受けとったデータを描画する。

makoto0306
Ruby, DB, React
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
ユーザーは見つかりませんでした