删除友谊

时间:2012-12-09 16:31:09

标签: ruby-on-rails

试图解决这个问题已经有一段时间但是无法弄清楚我做错了什么。我只想破坏两个用户之间的友谊。

视图如下所示:

友谊/ 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 %>

友谊控制器

    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  

我收到此错误:

  

没有路线匹配[DELETE]“/ friendships”

I但是当我运行rake路线时,看起来我有路径:

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

1 个答案:

答案 0 :(得分:2)

这一行

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

应该是

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

(单数,不是复数形式)

friendship是友谊对象的一个​​实例,获取它的方式取决于模型代码。最有可能的是,像

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

应该有用。