LoginSignup
1
1

More than 3 years have passed since last update.

Railsでいいね機能(Ajax)を実装した時の疑問について

Posted at

概要

ポートフォリオを作成していてAjaxを使ったいいねを実装している時にうまくAjaxの処理が動かず
この記事
https://qiita.com/naota7118/items/e009eff939b5a764672d#%E4%BB%8A%E5%9B%9E%E8%8B%A6%E5%8A%B4%E3%81%97%E3%81%9F%E3%81%A8%E3%81%93%E3%82%8D
を読んで解決した。
しかし、
この記事にもあるとおり

<%= button_to question_like_path(question, id: question.likes[0].id), class:"btn btn-primary like", method: :delete , remote:true do %>

このコードで自分のいいねを消すdestroyアクションが動く理由がわからなかった
(id: question.likes[0].idだとquestionに結びついたlikesの0番目のいいねを問答無用に消すから自分のいいねを消す保証は取れなくね?と思った)

頭を捻って理解したので備忘録として残しておく。

結論

destroyアクション側で削除するいいねをcurrent_userでfind_byしているから

  def destroy
    @like = @question.likes.find_by(user_id: current_user.id)
    @like.destroy
    #あとでAjaxを実装するまでとりあえずルート
    respond_to do |format|
      format.html { redirect_to @like.question || root_url}
      format.js
    end
  end
likeを指定しないとURLの生成ができないためlikes[0]で代用している。
しかし、消す対象のいいねのユーザーは```current_user```メソッドを使って
destroyアクションでfind_byして取得しているためここでは関係ない。

見た目に騙された。。。

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