I implemented a like function in Rails, but when I used this function, the following problems occurred.
--Since the entire page is re-rendered, it involves unnecessary processing. --Since page transitions are involved, even if you make a like or comment at the bottom of the page, it will transition to the top of the page, reducing usability.
Therefore, I decided to add Ajax function and improve usability without accompanying page transition.
The first implementation method I thought was to use JavaScript / jQuery to fire Ajax processing, but when I investigated, Rails had `` `link_toetc. It was said that Ajax processing can be used by adding
remote: true``` to the method of. Unlike the implementation method I thought at first, it was simple, so I immediately implemented it with that method.
--The posting function and like function have already been implemented. --The like function that is implemented is of the type that involves page transition when the like button is pressed. --For the above, it is assumed that Ajax processing is implemented by asynchronous communication. This article is an introduction to the steps taken in that implementation.
First, let `` app / views / posts / show.html.erb``` make the like button
app / views / likes / _like.html.erb``` to
`render``` ..
erb:app/views/posts/show.html.erb
#···abridgement
<div class="post-like mr-auto">
<%= render partial: 'likes/like', locals: { post: @post, like: @like } %>
</div>
#···abridgement
Add the Ajax function by adding `remote: true``` to the arguments of the like function
delete``` and ``
post```.
erb:app/views/likes/_like.html.erb
<% if current_user.already_liked?(post) %>
<%= link_to 'Like', post_like_path(post, like), method: :delete, class:'post-like__cancel', remote: true %>
<% else %>
<%= link_to 'Like', post_likes_path(post), method: :post, class:'post-like__enable', remote: true %>
<% end %>
By adding it, you will be able to execute the following processing after clicking each link.
-- delete
method → `app / views / likes / destroy.js.erb``` file execution --``` post``` method → Execute the file
`app / views / likes / create.js.erb```
Next, the js.erb
file is a method of Controller
such as `@ post``` or
@like``` as shown in the code below. You can use the defined instance variables. this is convenient.
erb:app/views/likes/destroy.js.erb
$('.post-like').html('<%= j(render partial: 'likes/like', locals: { post: @post, like: @like }) %>');
erb:app/views/likes/create.js.erb
$('.post-like').html('<%= j(render partial: 'likes/like', locals: { post: @post, like: @like }) %>');
The result is as follows. I was able to confirm that it was working without page transitions.
In addition, I was able to implement a follow function and comments. In the future, I will also create a search function, so I will use Ajax as well.
Recommended Posts