When deleting a user from friends, it gives an error:

ActiveRecord::RecordNotFound in FriendshipsController#destroy
Couldn't find Friendship with 'id'=2 [ WHERE "friendships"."user_id" = ? ]

friendships controller:

 class FriendshipsController < ApplicationController def create @friendship = current_user.friendships.build(:friend_id => params[:friend_id]) if @friendship.save flash[:success] = "Пользователь добавлен в друзья." redirect_to root_path else flash[:alert] = "Невозможно добавить в друзья." redirect_to root_path end end def destroy @friendship = current_user.friendships.find(params[:id]) @friendship.destroy flash[:notice] = "Пользователь удален из друзей." redirect_to current_user end end 

Controller users :

 def my_friends @friendships = current_user.friends end 

Presentation file in the users controller:

 <% @friendships.each do |friend| %> <%= friend.name %> <%= link_to "Профиль пользователя", user_path(friend), class: "button" %> <%= link_to "Удалить из друзей", friendship_path(friend), method: :delete %> <% end %> 
  • Links between models lead. - D-side
  • User: has_many: friendships has_many: friends, through:: friendships has_many: inverse_friendships,: class_name => 'Friendship',: foreign_key => 'friend_id' has_many: inverse_friends,: through =>: inverse_friendships,: source =>: user - lif3ar
  • Friendship: belongs_to: user belongs_to: friend,: class_name => 'User' - lif3ar

1 answer 1

From the presented code it is not clear, but I understand that in the User model, something like

 has_many :friendships has_many :friends, through: :friendships, class_name: "User" 

If so, then the problem is:

 @friendships = current_user.friends 

But

 def destroy @friendship = current_user.friendships.find(params[:id]) # ... end 

Those. the form sends the friend (user) ID, and the controller waits for the "friend" ID (intermediate label). The easiest option will probably be this:

 def destroy @friendship = current_user.friendships.find_by(friend_id: params[:id]) #... end