[RAILS] I tried to implement the like function by asynchronous communication



Many articles have already been published, but I would like to write it as a memorandum of my own.

Benefits of asynchronous communication

By personally learning "why the technology is used" first, I feel that understanding is quick because the purpose is clear.

1. Only a part of the page can be updated without changing the page.

To be honest, I think it's quite annoying if the page is changed every time you like it. However, by using asynchronous communication, you can comment, like, and edit users without going through __page transitions! __


Step ① Send a JS format request to the server

First, if it is not asynchronous communication, the terminal at the time of like execution behaves as follows. スクリーンショット 2020-10-29 17.03.56.png The request format is output in the red circle part of the image. In this case, it means that the communication is in HTML format!

I want to put this in JS format ...!


<%= link_to post_favorites_path(post), method: :DELETE, remote: true do %>

In this way, you can send a JS format request by adding remote: true to the link of the like button. スクリーンショット 2020-10-29 17.15.15.png

Step ② Create a partial template for the like button

In order to implement asynchronous communication, the changes need to be partial templates. Specifically, prepare a box of "likes" that you want to partially update, It is an image that switches the display depending on whether you like it or not.


  <% if post.favorited_by?(current_user) %>
    <%= link_to post_favorites_path(post), method: :DELETE, remote: true do %>
      <span class="btn btn-danger">Like</span>
    <% end %>
  <% else %>
    <%= link_to post_favorites_path(post), method: :POST, remote: true do %>
      <span class="btn btn-primary">Like</span>
    <% end %>
  <% end %>

Create a partial template views / posts / _favorites.html.erb, Move the like button part here. Then call the partial template created earlier in the original index.html.


<div class="main_contents">
    <% @posts.each do |post| %>
        <div class="post_contents">
          <h2><%= link_to post.title, post_path(post.id) %></h2>
          <%= post.content %>

         <!--↓ Add(Where you want to partially update)↓ -->
          <div id="favorite-<%= post.id %>">
             <%= render 'posts/favorites', post: post %>
         <!--↑ Up to here ↑-->
  <% end %>

Step ③ Create a js.erb file

For HTML format requests, the view file is views / controller name / action name.html.erb Call the file of.

However, for JS format requests, views / controller name / action name.js.erb Call the file of.

This time, I'm implementing the like function using the create and destroy actions of the favorites controller. views / favorites / create.js.erb and views / favorites / destroy.js.erb Create a file.


 #id="favorite-<%= @post.id %>"It is a process to partially update only the HTML of this part with render
$("#favorite-<%= @post.id %>").html("<%= j(render 'posts/favorites',  post: @post ) %>");


$("#favorite-<%= @post.id %>").html("<%= j(render 'posts/favorites',  post: @post ) %>");

Step ④ Delete the controller redirect


    def create
      @post = Post.find(params[:post_id])
      favorite = current_user.favorites.build(post_id: @post.id)
      redirect_to root_path #← Delete this line

    def destroy
      @post = Post.find(params[:post_id])
      favorite = current_user.favorites.find_by(post_id: @post.id)
      redirect_to root_path #← Delete this line


With the above procedure, you can implement desynchronization of the like function!


Ajax (asynchronous communication) is summarized with an emphasis on comprehensibility (with a demo using Rails)

Recommended Posts

I tried to implement the like function by asynchronous communication
[Swift] I tried to implement the function of the vending machine
[Rails] I tried to implement "Like function" using rails and js
I tried to implement the Iterator pattern
I tried to implement Ajax processing of like function in Rails
I tried to implement the image preview function with Rails / jQuery
I tried connecting the dot counter to the MZ platform by serial communication
I tried to implement the Euclidean algorithm in Java
[Rails] I implemented the validation error message by asynchronous communication!
I tried to explain the method
I tried to build the environment little by little using docker
[Java] I tried to make a maze by the digging method ♪
I tried to summarize the methods used
[Swift] How to implement the countdown function
I tried to summarize the Stream API
I tried to use Selenium like JQuery
I tried to implement ModanShogi with Kinx
I tried to implement polymorphic related in Nogizaka.
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I tried to organize the session in Rails
[Swift] How to implement the LINE login function
Posting function implemented by asynchronous communication in Rails
[swift5] How to implement the Twitter share function
I tried to implement deep learning in Java
How to implement the breadcrumb function using gretel
[For beginners] How to implement the delete function
[Swift] How to implement the fade-in / out function
I tried to set tomcat to run the Servlet.
I tried to implement a server using Netty
Rails API mode I tried to implement the keyword multiple search function using arrays and iterative processing.
[Rails, JavaScript] Implemented like function (synchronous / asynchronous communication)
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
I tried to implement file upload with Spring MVC
I tried to organize the cases used in programming
I tried using the Server Push function of Servlet 4.0
I tried to implement TCP / IP + BIO with JAVA
I tried to implement Firebase push notification in Java
I tried to summarize the state transition of docker
I tried to decorate the simple calendar a little
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I tried to make a login function in Java
I tried to implement Stalin sort with Java Collector
[Java] I tried to implement Yahoo API product search
I want to add a delete function to the comment function
I tried to investigate the mechanism of Emscripten by using it with the Sudoku solver
I tried to operate home appliances by holding a smartphone over the NFC tag
[Swift] I tried to implement exception handling for vending machines
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
I tried to increase the processing speed with spiritual engineering
[JDBC] I tried to access the SQLite3 database from Java.
I tried to summarize the basics of kotlin and java
I want to implement a product information editing function ~ part1 ~
I tried the Docker tutorial!
I tried the VueJS tutorial!
I tried to summarize the basic grammar of Ruby briefly
[Rails] I tried to implement batch processing with Rake task
I tried to build the environment of WSL2 + Docker + VSCode
I tried the FizzBuzz problem
I tried to develop the cache function of Application Container Cloud Service in the local environment