Reputation: 9806
I've created a follow/unfollow feature in my rails/angular app following https://www.railstutorial.org/book/following_users guide. But when I want to unfollow a friend the method removes the id of the user.
The removeFollower function in my template,
%ul{"ng-repeat" => "follower in followers"}
%li
{{ follower.name }}
%a{"ng-click" => "removeFollower(follower)"} Remove
The removeFollower function in my controller,
$scope.removeFollower = function(follower){
console.log (follower)
console.log (follower.name)
removeFollower.removeFollower(follower).then(function(){
},function(){
}).then(init);
Notification.success(follower.name + ' is verwijderd als vriend.');
}
And the removeFollower service,
app.factory('removeFollower', ['$http', function($http) {
return {
removeFollower: function(follower) {
var follower_id = parseInt(follower.id);
var follower_name = (follower.name)
console.log (follower_id)
return $http.delete('/relationships/'+follower_id + '.json');
}
};
}])
And the destroy method in my relationship_controller,
def destroy
@user = Relationship.find(params[:id]).followed
current_user.unfollow(@user)
redirect_to root_url
end
So when I unfollow a user the method removes the wrong object (I think).
ActiveRecord::RecordNotFound (Couldn't find Relationship with 'id'=3): app/controllers/relationships_controller.rb:13:in `destroy'
The id here is the user id of the user I'm trying to unfollow and I think it should be the id of the record.
Upvotes: 0
Views: 59
Reputation: 4322
You are sending the follower_id
in you delete
request $http.delete('/relationships/'+follower_id + '.json');
so you have one of two options.
Your @user
should not be an instance of a Relationship
but rather an instance of User
model
def destroy
@user = User.find(params[:id])
current_user.unfollow(@user)
redirect_to root_url
end
And your unfollow(user)
method should destroy a Relationship
instance that is Relationship.where(follower_id: self.id, followed_id: user.id).destroy
Or send the follower
id to the controller directly and change your destroy method to:
def destroy
current_user.relationships.where(follower_id: params[:id]).destroy_all
redirect_to root_url
end
Upvotes: 1