1
0

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 1 year has passed since last update.

Rails いいね機能の非同期を実装する際の注意するべきポイント

Last updated at Posted at 2022-02-24

いいねの非同期を行う際、何回かエラーでつまづいた。
そんな時に確認するべきポイントをまとめる!!

1.jQueryがちゃんと読み込まれているか

Gemfile.
gem 'jquery-rails'

その後、bundle install を忘れずに。

app/assets/javascripts/application.js
//= require jquery
//= require rails-ujs
//= require jquery_ujs
webpacker/environment.js
const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
    new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery'
    })
)

module.exports = environment
app/javascript/packs/application.js
require('jquery')

jQueryはこの辺り。。

2.link_toにremote:true

_like_button.html.erb
= link_to photo_like_path(@photo), method: :post, remote: true do 
_lunike_button.html.erb
= link_to photo_like_path(@photo), method: :delete, remote: true do 

ajax用のviewファイル内のlink_toにremote: true を追加。
HTMLリクエストではなく、JavaScriptのリクエストがコントローラに送られる。

HTML
→画面にリダイレクトする(ページを読み込む)
JavaScript
→いいね部分のみの更新(ページ読み込みなし)

3.renderでテンプレートを読み込む&idで変更箇所に名前をつける

<div id="like-button-<%= @photo.id %>">
  <% if current_user.likes.exists?(photo_id: @photo.id) %>
    <%= render 'likes/unlike_button', photo: @photo %>
  <% else %>
    <%= render 'likes/like_button', photo: @photo %>
  <% end %>
 </div>

4.js.erbファイル

create.js.erb
$("#like-button-<%= @photo.id %>").html("<%= j(render 'unlike_button', photo: @photo) %>")
destroy.js.erb
$("#like-button-<%= @photo.id %>").html("<%= j(render 'like_button', photo: @photo) %>")

以上。抜かりないよう。

参考

https://qiita.com/hapiblog2020/items/3ba7e7edc02f01d987b9
https://qiita.com/masahisa/items/eaacb0c3b82f4a11fc13

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?