我似乎無法讓Amistad友誼正常工作。我收到以下錯誤:如何創建好友?
ActiveRecord::RecordNotFound in FriendshipsController#update
Couldn't find Friendship with id=29
我也使用devise和cancan。我遵循維基頁面上的創業板設置,並按this related post中所述創建了我的控制器。
class FriendshipsController < ApplicationController
before_filter :authenticate_user!
def index
@friends = current_user.friends
@pending_invited_by = current_user.pending_invited_by
@pending_invited = current_user.pending_invited
end
def create
@friend = User.find(params[:user_id])
@friendship_created = current_user.invite(@friend)
if @friendship_created
redirect_to users_path, :notice => "Your friend request is pending"
end
end
def update
@friend = User.find(params[:user_id])
@friends = current_user.friends
@pending_invited_by = current_user.pending_invited_by
redirect_to users_path, :notice => "You are now friends!"
end
def destroy
@friend = User.find(params[:user_id])
@friendship = current_user.send(:find_any_friendship_with, @friend)
if @friendship
@friendship.delete
@removed = true
redirect_to users_path, :notice => "You are no longer friends!"
end
end
def createblock
@friend = User.find(params[:user_id])
current_user.block @friend
redirect_to users_path, :notice => "You have blocked #{@friend.first_name}"
end
end
我通過以下方式循環檢查用戶的當前狀態並提供適當的操作。
<% if current_user.friend_with? user %>
<%= link_to "Unfriend", friend_path(user), :method => "delete", :class => 'btn btn-mini' %>
<% elsif current_user.invited? user %>
<span class="btn btn-mini disabled">Pending</span>
<% elsif user.invited? current_user %>
<%= link_to "Accept", friend_path(user), :method => "put", :class => 'request-approve btn btn-mini' %>
<%= link_to "Decline", friend_path(user), :method => "delete", :class => 'request-decline btn btn-mini' %>
<% else %>
<%= link_to "Add friend", friends_path(:user_id => user), :method => "post", :class => 'btn btn-mini' %>
<% end %>
想通了,看看有什麼友誼表看起來像在我的架構將是有益的:
create_table "friendships", :force => true do |t|
t.integer "friendable_id"
t.integer "friend_id"
t.integer "blocker_id"
t.boolean "pending", :default => true
end
add_index "friendships", ["friendable_id", "friend_id"], :name => "index_friendships_on_friendable_id_and_friend_id", :unique => true
我理解的錯誤只是想不通這應如何改變。我認爲我的問題是,我傳遞了一個朋友ID,它期待着一個友誼ID。這個解決方案唯一的問題是,我可以找到的每個示例或帖子都建議傳遞user_id,就像上面這個帖子中回答者聲明gem開發者提供了他所回答的代碼一樣。
我想吃什麼,我需要在我的更新方法就是更換:
@friend = User.find(params[:id])
有了這個:
@friendship = Friendship.find_by_friend_id(params[:id])
編輯 我能成功申請的朋友,我還是無法接受或拒絕朋友。我列出了一個用戶列表,點擊「添加朋友」鏈接可以正確創建友誼數據庫中的記錄。如果我以最近請求的用戶身份登錄,並嘗試接受請求,那麼我會收到上述錯誤。如果我試圖拒絕請求,也會發生這種情況。
您要求看到的amistad寶石的朋友方法,這裏是the code for that method。至於我的Ruby日誌,顯示錯誤的部分非常長,所以我將它包含在this gist中。
你可以顯示'current_user.friends'的代碼,它在那裏失敗吧?我的意思是,在日誌中,ruby抱怨哪一行? – juanpastas
@juanpastas我已更新以證明您的問題的答案 – Thomas
您的'development.log'說'ActiveRecord :: RecordNotFound(無法找到id = 32的友誼)'在您問題'update'正在執行'User.find'你能解釋一下嗎? – juanpastas