0
1

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.

【Rails入門】Ajaxを導入する

Last updated at Posted at 2020-08-19

0.前準備

前準備として、コントローラを作成します。

$ rails g controller Practice index 

1. Viewを整える

app/views/practice/index.html.erb
<h1>Ajaxを使ってみよう</h1>
<!-- :remote => trueの部分で、turbolinkを有効にする -->
<%= form_tag(url_for(:action => 'index'), :remote => true) do %>
  <%= text_field_tag :title %>
  <%= submit_tag "タイトルを変更する" %>
<% end %>
  • turbolink => turbolinkを使えば、ajaxが自動的に使える。

2. Controllerを修正する

app/controllers/practice_controller.rb
def index
  @title = params[:title]
  # respond_toメソッド => 結果をどのフォーマットで返すかを指定している
  respond_to do |format|
    # turbolinkが有効でないとき
    format.html
    # turbolinkが有効なとき
    format.js # => 次にindex.js.erbが呼ばれる
  end
end
  • respond_toメソッド => あるオブジェクトが、特定のメソッドを持っているかどうかを調べて、trueまたはfalseを返す。

3. routeを指定する

indexにポストしているので、app/config/routes.rbに以下のようにリソースを振り分ける。

app/config/routes.rb
get 'practice/index'
post 'practice/index' # 追加

4. JSを指定する

format.jsで指定したindex.js.erbを、app/views/practice/に作成する。

app/views/practice/index.js.erb
$('h1').html("<%= @title %>");

5. jQueryを使えるようにする

Rails 5.xからjQueryが標準でサポートされなくなったとかあるらしく、自分で設定する必要があるらしい。

app/assets/javascripts/application.js
//= require jquery <= 追加
//= require rails-ujs
//= require turbolinks
//= require_tree .
Gemfile
gem 'jquery-rails'

gemを追加して、

$ bundle install

5. Ajaxの動きを確認する

$ rails s

サーバーを起動し、http://localhost:3000/practice/indexにアクセスする。

スクリーンショット 2019-09-16 21.40.47.pngスクリーンショット 2019-09-16 21.40.57.png

非同期処理に成功しました。

6. 最後にRailsに置けるAjaxの流れを確認する

6-1. turbolinksまたはjQueryなどを使って、JavascriptでXMLHttpRequestRequestを送り任意のアクションを実行する(今回はindexアクション)

6-2. アクションが実行される(この間にDBとのやりとりができる)。また、どの形式でデータを返却するかを指定することができる。(Javacript、JSON、XMLなど)

6-3. 選択されたデータ形式で(今回はJavascript)ファイルを自動的に検索して、ファイル内容を実行する(今回はindex.js.erb)ここで、HTML&CSSが変更されて、ajaxが完結する。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?