フォロー・フォロワー機能のコントローラ、ビュー

maa0917.hatenablog.com

以前の続きです。

(views/users/show.html.erb)

<%= render partial: 'users/follow_form', locals: { user: @user } %>
$ rails g controller Relationships create destroy

(routes.rb)

resources :relationships, only: [:create, :destroy]

(views/users/_follow_form.html.erb)

<div id="follow_form_<%= user.id %>">
  <% unless current_user.active_relationships.find_by(followed_id: user.id) %>
    <%= form_with(model: current_user.active_relationships.build(followed_id: user.id))  do |f| %>
      <%= f.hidden_field :followed_id %>
      <%= f.submit 'フォローする' %>
    <% end %>
  <% else %>
    <%= form_with(model: current_user.active_relationships.find_by(followed_id: user.id), method: :delete) do |f| %>
      <%= f.submit 'フォロー解除' %>
    <% end %>
  <% end %>
</div>
class RelationshipsController < ApplicationController
  before_action :authenticate_user!
  respond_to? :js
  def create
    relationship = current_user
                  .active_relationships
                  .build(followed_id: params[:relationship][:followed_id])
    relationship.save
    @user = User.find(relationship.followed_id)
  end

  def destroy
    relationship = Relationship.find(params[:id])
    relationship.destroy
    @user = relationship.followed
  end
end

(users/relationships/create.js.erb)

$("#follow_form_"+"<%= @user.id %>").html("<%= j(render partial: 'users/follow_form', locals: { user: @user}) %>")
$("#follow_form_"+"<%= @user.id %>").html("<%= j(render partial: 'users/follow_form', locals: { user: @user}) %>")