I want to be able to allow users to vote on a resource using AJAX, however, I’m not exactly sure how to get the current_user’s id inside my resource’s controller.
I’ve searched around and I’ve read a lot of suggestions to save the user_id as a hidden field, and then using that to send the AJAX request, but wouldn’t that open me up to security vulnerabilities? Any malicious user could just alter the user_id and then vote as random user he chooses.
What’s the standard way to get the current_user’s id for an AJAX request?
Thanks
If the whole thing is behind authentication, you shouldn’t need to store the user_id in the view, or spend any effort passing it around. Simply access
current_user(orcurrent_user.id) in the controller, as normal.By “the whole thing is behind authentication” I mean the controller with the view that has the interface to vote, as well as controller of the destination of the AJAX request should both have
before_filter :authenticate_user!, or derive from a class that does. If this is the case, devise will identify the user in the same way that it does for every other authenticated request. It doesn’t matter that the request is JSON, other than you may need to adjust your unauthorized behavior to include a javascript redirect to your login, if you don’t already have something like that.