rails クソコードを簡潔にしたいのですがどうすれば良くなるでしょうか?
いいね機能をposts/showのみではなくindexページでも行えるようにしたいのですが、その際いいねボタンを押すとshowページに遷移されてしまうのを解消しようと思いやったらクソコードが出来上がってしまいました
routes.rb
get "likes/:post_id/indexcreate" => "likes#indexcreate"
get "likes/:post_id/indexdestroy" => "likes#indexdestroy"
get "likes/:post_id/create" => "likes#create"
get "likes/:post_id/destroy" => "likes#destroy"
likes_controller.rb
class LikesController < ApplicationController
before_action :authenticate_user
def create
@like = Like.new(user_id: @current_user.id, post_id: params[:post_id])
@like.save
redirect_to("/posts/#{params[:post_id]}")
end
def destroy
@like = Like.find_by(user_id: @current_user.id, post_id: params[:post_id])
@like.destroy
redirect_to("/posts/#{params[:post_id]}")
end
def indexcreate
@like = Like.new(user_id: @current_user.id, post_id: params[:post_id])
@like.save
redirect_to("/posts/index")
end
def indexdestroy
@like = Like.find_by(user_id: @current_user.id, post_id: params[:post_id])
@like.destroy
redirect_to("/posts/index")
end
end
posts/index.html.erb
<% if @current_user && Like.find_by(user_id: @current_user.id, post_id: post.id) %>
<%= link_to("/likes/#{post.id}/indexdestroy", {method: "post"}) do %>
<span class="fa fa-heart liked-btn"></span>
<% end %>
<% else %>
<%= link_to("/likes/#{post.id}/indexcreate", {method: "post"}) do %>
<span class="fa fa-heart unliked-btn"></span>
<% end %>
<% end %>
<%= @post_like_count[post.id] %>
posts/show.html.erb
<% if @current_user && Like.find_by(user_id: @current_user.id, post_id: @post.id) %>
<%= link_to("/likes/#{@post.id}/destroy", {method: "post"}) do %>
<span class="fa fa-heart liked-btn"></span>
<% end %>
<% else %>
<%= link_to("/likes/#{@post.id}/create", {method: "post"}) do %>
<span class="fa fa-heart unliked-btn"></span>
<% end %>
<% end %>
<%= @likes_count %>
最後まで読んでいただきありがとうございます
初心者のため説明が下手ですがよろしくお願いします
0 likes