LoginSignup
1
1

More than 3 years have passed since last update.

Railsで非同期通信で実装する投稿機能

Last updated at Posted at 2020-11-14

はじめに

今回は非同期通信による投稿機能を実装していきます。
今回は非同期処理を行う事にフォーカスを当てるためすでに画面遷移ありの投稿機能が実装されている状態からのスタートとなります。
jsの理解のため、素のjsでの記述となります。
また初学者のため間違え等ありましたらご指摘頂けると幸いです。

手順1 remote: tureを追加

入力フォームにremote: tureを追記しましょう!

<%# タスク入力フォーム %>
<div class="task-contents">
    <%= form_with model: @category, id: 'new_tasks', class: 'new_tasks' do |f| %>
     <div class="task-field">
       <%= f.text_field :task %>
     </div>
     <div class="task-actions">
       <%= f.submit "+" %>
     </div>
    <% end %>
</div>

ここでどこにremote:tureがあるんだ?と思う方もいると思うのですがform_withを使うとデフォルトでajax通信を行う仕様になっているのでform_withを使う場合は特に記述は不要です。逆にajax通信にしない場合はlocal: trueにすると通常のリクエストになります。
form_forを使う方はremote: trueオプションを忘れずに追記してください。
心配な方は開発ツールなどで確認するとdata-remote="true"となっているはずなので確認してみると良いと思います。

手順2 コントローラーの記述

def create
      @category = Category.new(category_params)
      @category.save
      @categories = current_user.categories.all
end

一般的な保存機能を行う記述ですが@categories = current_user.categories.allの記述はこの後のjsに渡す情報として必要なので記述しています。

手順3 create.js.erbにJavaScriptの記述をする

remote: trueにより返却される内容がHTMLではなくアクション名.js.erbファイルが読み込まれるようになっているのでcreate.js.erbファイルを作成します

(function(){
  document.querySelector(".task-lists").innerHTML =  '<%= j(render 'categories/index', categories: @categories) %>'
  document.querySelector("#category_task").value = ''
})();

.innerHTMLでHTMLの中身を書き換えています。

'<%= j(render 'categories/index', categories: @categories) %>'
ここで@categoriesを渡すために手順2で定義しています。
document.querySelector("#category_task").value = ''
この記述により入力入力フォームを空にしています。

最後に

以上で非同期での投稿機能が完成です!
重要なのはajax通信のデータの流れを理解できればそれぞれの処理はシンプルなので理解しやすいかなと思います。
初学者のためもっと良い記述があればご教授頂けると幸いです。

非同期削除などの記事もよければどうぞ〜
https://qiita.com/shantianchengyilang316/items/10ab2d84f6cfcfd29def

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