OXp1845
OXp1845

Reputation: 493

Deleting friendships

Been trying to solve this for quite some time but can't figure out what I am doing wrong. I am simply trying to destroy a friendship between two users.

The view looks like this:

friendships/index.html.erb

<% @users.each do |user| %>

<% if user.id != current_user.id %> 
<%=h user.name %> 
<%if current_user.is_friend? user %>
<%= link_to "Destroy", friendships_path(:friend_id => user), :method => :delete %> 

<%else%>
<%= link_to "Add friend", friendships_path(:friend_id => user), :method => :post %> 
<% end %>
 <% end %>

<% end %>

friendship controller

    def index
      @users = User.all
    end

    def show
     @user = current_user
    end

 def create
   @friendship = current_user.friendships.build(:friend_id => params[:friend_id])
   if @friendship.save
     flash[:notice] = "Added friend."
     redirect_to root_url
   else
     flash[:error] = "Error occurred when adding friend."
     redirect_to root_url
   end
 end

def destroy
  @friendship = current_user.friendships.find(params[:id])
  @friendship.destroy
  flash[:notice] = "Successfully destroyed friendship."
  redirect_to root_url
end  

I am getting this error:

No route matches [DELETE] "/friendships"

I But it looks like I have the path when I run rake routes:

     friendship GET    /friendships/:id(.:format)         friendships#show
                PUT    /friendships/:id(.:format)         friendships#update
                DELETE /friendships/:id(.:format)         friendships#destroy

Upvotes: 0

Views: 347

Answers (1)

dimuch
dimuch

Reputation: 12818

This line

<%= link_to "Destroy", friendships_path(:friend_id => user), :method => :delete %>

should looks like

<%= link_to "Destroy", friendship_path(friendship), :method => :delete %>

(singular, not plural form)

The friendship is an instance of Friendship object, the way to get it depends on the model code. Most likely, something like

<%= link_to "Destroy", friendship_path(current_user.friendships.find_by_friend_id(user)), :method => :delete %>

should work.

Upvotes: 3

Related Questions