2015-12-30 62 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当前用户