我有傳統的友誼模式:Rails 3友情模型:如何忽略好友請求?
用戶模型有:
has_many :friendships, :dependent => :destroy
has_many :friends, :through => :friendships, :dependent => :destroy
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id", :dependent => :destroy
has_many :inverse_friends, :through => :inverse_friendships, :source => :user, :dependent => :destroy
我想定義的狀態爲「朋友」,只在一個朋友請求已發送,以及由其他用戶接受。一切正常,但我沒有設法處理「忽略朋友請求」部分。
我想要做的是:在用戶個人資料頁面上,有來自其他用戶的請求列表,等待批准。然後用戶可以接受朋友請求(然後成爲朋友)或拒絕它(然後友誼關係被破壞)。
下面是一段代碼,在友誼控制器,當塊:
<h2 class="small_v_space">Waiting your approval</h2>
<ul>
<% for user in @user.inverse_friends %>
<% if user.friends.exists?(@user) and not @user.friends.exists?(user) %>
<li>
<%=h user.name %>
(<%= link_to "Accept", friendships_path(:friend_id => user), :method => :post %>,
<%= link_to "Ignore", friendship_path, :controller => :friendships, :method => :delete %>)
</li
<% end %>
<% end %>
</ul>
的問題是,如果我不喜歡這樣,刪除方法將刪除最後添加的關係,而不是一個鏈接到忽略按鈕。
讓我們用一個例子工作: 這裏是我想摧毀的關係: USER_ID:10 Friend_id:6 Friendship_id:18
我在 '顯示' 頁面(配置文件),其user_id是6.我看到用戶10已經提出了一個我想忽略的朋友請求。即使我設法提取適當的Friendship_id,這樣做的:
<%= link_to "Ignore", friendship_path(Friendship_id), :controller => :friendships, :method => :delete %>)
它導致「無法找到ID友誼= 18 [其中USER_ID = 6]」
有誰知道我怎麼能調用destroy在這種情況下對正確的關係採取行動?還是應該以不同的方式進行?
非常感謝您的任何線索!
EDIT
銷燬友誼控制器的動作:
def destroy
@friendship = current_user.friendships.find(params[:id])
if @friendship.friend.friends.exists?(current_user)
@friendship.destroy
flash[:notice] = "Removed friendship."
else
@friendship.destroy
flash[:notice] = "Removed friend request."
end
redirect_to current_user
end
編輯2:
class Friendship
belongs_to :user
belongs_to: :friend, :class_name => 'User'
end
用戶A發送好友請求給用戶B(A =用戶,B =班級實例中的朋友) 。如果B接受請求,則創建另一個實例(B =用戶,A =朋友)。如果存在關係A-> B和B-> A,則A是B的朋友。否則,請求保持掛起(或可以被忽略,被拒絕...)。
我認爲你過於複雜的事情。我很確定要做你想做的事情,你需要的只是一個朋友和友誼模型,而在友誼模型中你會有一個叫做狀態的int變量,或者根據是否有不同的值該關係已被接受與否。但那不是重點。 '<%= link_to「忽略」,友誼路徑(Friendship_id),:方法=>:刪除%>'應該可以工作,你能否顯示你的友誼控制器的銷燬行爲? – Ashitaka 2012-03-20 19:24:56
@ Ashshaka:謝謝你的回覆!我在問題中添加了銷燬行爲。你是對的,還有其他方法可以做到這一點,但我覺得我可以通過這樣做來學習很多東西。問題是,在user_6的顯示頁面內,即使正確的friendship_id被傳遞,它失敗,因爲它說「無法找到Friendship_id = 18 WHERE user_id = 6 ...我想以某種方式擺脫此user_id = 6 ...我花了幾個小時嘗試大量的選項,現在感覺有點困惑: -/...謝謝! – citraL 2012-03-20 19:35:37
好的,爲了解決這個問題,我們需要更多的信息,請顯示你的關係模型。另外,你如何區分作爲你的朋友的用戶和向你發送朋友請求的用戶? – Ashitaka 2012-03-21 12:52:02