2015-12-30 65 views
2

我已經在我的rails/angular應用程序中創建了一個簡單的友誼功能,但是我在使用破壞功能時遇到了一些麻煩。我想到了一個解決方案,但不確定它是否可行,以及如何創建它。刪除與用戶ID相關的記錄

當友誼創建存儲在友誼臺的新紀錄(友誼),

create_table "friendships", force: :cascade do |t| 
    t.integer "user_id" 
    t.integer "friend_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

這裏是友誼的JSON輸出。該id是友誼的id,friend_id是已經參與了友誼的用戶的id。

{"id":8,"friend_id":2}, 
{"id":9,"friend_id":3}, 
{"id":10,"friend_id":4} 

在我的友誼控制器我有這個,

def index 
    friends = current_user.friends.as_json(:only => [:id, :friend_id, :name]) 
    render :json => friends 
end 

這使得以下。

{"id":2,"name":"Jan Jansen"}, 
{"id":3,"name":"Kees Keesen"}, 
{"id":4,"name":"Piet Pietersen"} 

正如您所見,用戶的id與friend_id的友誼一致。

現在來解決問題。這是我的刪除功能,

def destroy 
    @friendship = current_user.friendships.find params[:id] 
    @friendship.destroy 
    redirect_to root_url 
end 

這裏的問題是,傳遞的id是用戶的id而不是id友誼。所以,如果我現在刪除友誼,我會得到一個錯誤。

http://localhost:3000/friendships/4.json 404(未找到)

有用戶ID,friend_id和友誼ID之間的聯繫。是否有可能通過用戶ID和/或friend_id獲得友誼ID?

回答

2

是否可以通過用戶標識和/或friend_id獲取友誼標識?

我認爲你的模式是錯誤的。

您正在嘗試查找連接表的id;你應該尋找的是friend_id

def destroy 
    @friendship = current_user.friendships.find_by friend_id: params[:id] 
    @friendship.destroy 
    redirect_to root_url 
end 

這樣 - 如果你通過friend_id的破壞方法,它會發現,朋友current_user

#app/views/friendships/index.html.erb 
<%= current_user.friends.each do |friend| %> 
    <%= link_to "Unfriend", user_friendships_path(friend), method: :destroy %> 
<% end %> 

更新

如果你可以用它id查找一個friendship,你可能使用了has_many :through協會:

enter image description here

從上面的schema可以看出,HMT join tablesprimary key,你正試圖用find來查找。問題是這個主鍵絕對是沒有與它引用的其他表的關係。

由於您正在嘗試識別與current_user相關的friendship記錄,因此我推測您嘗試識別特定的friend。唯一的方法是查看friend_id列。

如果你有has_and_belongs_to_many(更簡單的實現上面的表格),你可以使用:

current_user.friendships.find params[:id] 

...因爲這直接鏈接到其他表(不參加)。

+0

哼!它似乎工作,但我不知道它是如何工作的。也許這是一個愚蠢的問題,但是@friendship到底是什麼?我認爲這是友誼表中的記錄。這就是爲什麼我想摧毀它。 –

+0

我會爲你寫一個更新 –

+0

如果你需要,我可以更新'has_and_belongs_to_many' –

1

似乎你想刪除一個友誼,所以找一個用戶friend_id

current_user.friendships.where(friend_id: params[:friend_id]).first 

所以

http://localhost:3000/friendships/4.json

將匹配路由:friendships/:friend_id當前用戶