我已經爲用戶設置了自我引用關係模型,以便彼此成爲朋友。我可以創建一個朋友請求(我的數據庫中有兩個條目,一個是友誼,一個是反向友誼),沒有任何問題。嘗試摧毀/拒絕友誼關係時未定義的方法「破壞」
雖然我拒絕拒絕朋友請求。我不斷收到這個錯誤,當我按下下降這需要我去摧毀行動:
NoMethodError in FriendshipsController#destroy
undefined method `destroy' for nil:NilClass
之一數據庫記錄,待友誼,即使我得到上述錯誤被破壞,如果我註釋掉@friendship2 = @user.friendships.find_by_friend_id(params[:id]).destroy
,另一個記錄也被破壞。所以它看起來像兩條線都單獨工作,但返回上述錯誤。
解決方案:它看起來像我的兩個銷燬語句引用相同的記錄。我在控制器中註釋了錯誤的代碼,並添加了適用於我的代碼。
這是我的友誼控制器:
class FriendshipsController < ApplicationController
before_filter :authenticate, :only => [:update, :create, :destroy]
def create
@user = User.find(current_user)
@friend = User.find(params[:friend_id])
params[:friendship1] = {:user_id => @user.id, :friend_id => @friend.id, :status => 'requested'}
params[:friendship2] = {:user_id => @friend.id, :friend_id => @user.id, :status => 'pending'}
@friendship1 = Friendship.create(params[:friendship1])
@friendship2 = Friendship.create(params[:friendship2])
redirect_to @friend
end
end
def destroy
@user = User.find(params[:user_id])
@friend = User.find(params[:id])
#@friendship2 = @user.friendships.find_by_friend_id(params[:id]).destroy
#@friendship1 = @friend.friendships.find_by_id(params[:user_id]).destroy
@friendship1 = @user.friendships.find_by_friend_id(@friend.id).destroy #removes the requested friendship
@friendship2 = @friend.friendships.find_by_friend_id(@user.id).destroy #removes the pending friendship
flash[:success] = "Removed."
redirect_to @user
end
end
這是我的用戶模型:
class User < ActiveRecord::Base
has_many :friendships, :dependent => :destroy
has_many :friends,
:through => :friendships,
:conditions => "status = 'accepted'",
:source => :friend
has_many :pending_friends,
:through => :friendships,
:conditions => "status = 'pending'",
:foreign_key => "user_id",
:source => :friend
has_many :requested_friends,
:through => :friendships,
:source => :friend,
:conditions => "status = 'requested'"
end
這是我的視圖(用戶/ show.html.erb):
<% if signed_in? && @user == current_user %>
<% unless current_user.pending_friends.empty? %>
<h2>Pending</h2>
<% current_user.pending_friends.each do |pending| %>
<%= pending.name %>
<%= link_to '[Accept]', friendship_path(:user_id => current_user, :id => pending), :method => :put, :confirm => "Accept?" %>
<%= link_to '[Decline]', friendship_path(:user_id => current_user, :id => pending), :method => :delete, :confirm => "Decline?" %>
<% end %>
<% end %>
<% end %>
我有兩個問題。
我從一些教程/討論有關the use of inverse_friendships看到的,但是這真的有必要嗎?到目前爲止,我還沒有看到這個需求,但是再一次,我只是編寫了我的創建和銷燬行動。
未定義的方法'destroy'錯誤是怎麼回事?
感謝您瀏覽這段文字! :D
謝謝你澄清這兩個問題。我仍然無法找到錯誤,並且也包含了我的觀點。我認爲問題出現在@ @ friendship1 = @ friend.friendships.find_by_id(params [:user_id])。destroy'行中。請原諒我的經驗不足(Rails仍然是新手)。我會繼續研究這一點。 – Huy 2012-03-30 06:13:31
謝謝你的幫助。這最終導致我發現答案。 – Huy 2012-03-30 08:43:22
不客氣:) – 2012-03-30 19:10:51