RESTful routing best practice when referencing current_user from route?

I would say that you are doing it correctly, just keep your current route as it is right now. And what you should do is to add a restriction in your controller instead. I would assume that you are using Rails, and working on users_controller.

class UsersController < ApplicationController::Base
  def edit
    if current_user.id == params[:id]
      # do your work
    else
      render :404
    end
  end
end

Or you could clean up your controller by moving the restriction into a callback instead:

class UsersController < ApplicationController::Base
  before_filter :restrict_user, only: [:edit]

  def edit
    # do your work
  end

  private
  def restrict_user
    render :404 unless current_user.id == params[:id]
  end
end

I would've added special routes for current user profile actions, in this case you don't have to check anything. Just load and display the data of current user. For example:

/my-profile/edit
/my-profile/newsfeed

It's not that RESTful but you don't have to put extra checks keeping your code clean.

If you still have to have (or want to have) a strict RESTful routes then I would use a before_filter and check if the id = current_user.id. If not then return 401 or 403.


I only want the current_user to have access to edit its profile. I don't want other users able to edit profiles that don't belong to them.

What I suggest is to use some authorization gems like pundit

Sample code:

class UserPolicy
  attr_reader :current_user, :model

  def initialize(current_user, model)
    @current_user = current_user
    @user = model
  end

  def edit?
    @current_user == @user
  end
end

Also with an authentication gem like Devise, only the current_user(the users who logged in) can only access and edit their profiles