Ruby Question

Following users on Ruby on Rails

I decided to upgrade code of https://www.railstutorial.org/book chapter 14 Following users. My code does not work, when

current_user
goes on another page and open following.
current_user
sees himself and want to unfollow like original instagram. unfollow button does not work

show_follow.html.erb:

<div class="line-gray-modals"></div>
<% if @users.any? %>
<% @users.each do |user| %>
<ul class="follow-list">
<li><%= image_tag(user.avatar.url(:thumb), :class => "img-cirkle") %></li>
<li >
<div class="modal-follow-ns" > <div class="bold"> <%= link_to user.username, user %></div> <br>
<div class="modal-follow-ns2"><%= link_to truncate(user.status, :length => 50) %></div></div>
</li>
<li class="button-modal">
<% unless user == current_user %>
<div id="follow_form">
<% if current_user.following?(user) %>
<%= form_for(current_user.relationships.find_by(followed_id: user),
html: { method: :delete },
remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>
<% else %>
<%= form_for(current_user.relationships.build(followed_id: user.id),
remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
<% end %>
</div>
<% end %>
<% if user == current_user %>
<%= form_for(@user.relationships.find_by(followed_id: user),
html: { method: :delete },
remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>
<% end %>
</li>
<%= will_paginate %>
<li> <div class="line-gray-modals"></div></li>
</ul>
<% end %>




relationships_controller.rb:

def create
@user = User.find(params[:relationship][:followed_id])
current_user.follow!(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end

def destroy
@user = Relationship.find(params[:id]).followed
current_user.unfollow!(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end


Terminal:

Completed 500 Internal Server Error in 10ms (ActiveRecord: 1.9ms)
NoMethodError (undefined method `destroy!' for nil:NilClass):
app/models/user.rb:28:in `unfollow!'
app/controllers/relationships_controller.rb:15:in `destroy'

Answer

Looking at the code below specially @user is probably nil. changing it to user does not make sense either. since you wanted to unfollow that user.

 <%= form_for(@user.relationships.find_by(followed_id: user), html: { method: :delete }, remote: true) do |f| %>

Instead, use current_user

  <%= form_for(current_user.relationships.find_by(followed_id: user), html: { method: :delete }, remote: true) do |f| %>