我已經在我的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友誼。所以,如果我現在刪除友誼,我會得到一個錯誤。
有用戶ID,friend_id和友誼ID之間的聯繫。是否有可能通過用戶ID和/或friend_id獲得友誼ID?
哼!它似乎工作,但我不知道它是如何工作的。也許這是一個愚蠢的問題,但是@friendship到底是什麼?我認爲這是友誼表中的記錄。這就是爲什麼我想摧毀它。 –
我會爲你寫一個更新 –
如果你需要,我可以更新'has_and_belongs_to_many' –