RESTful nested routes when 'current_user' is available

I’m working on a project with a Rails API that generates session tokens and allows use of a current_user method. My question is about RESTful nested routes.

Let’s say I have models User and Observation, and a user has_many observations. I want to be able to return all of the observations related to a particular user. This is how I was thinking to set up the routes:

resources :users do 
  resources :observations, only: [:index]
end

This gives me the following route (everything is in an api namespace):

/api/members/:user_id/observations

My question is, if the API requires generating a session to “log in” and the current_user method is available, should I have routes like this that require a :user_id to be used by someone who has already signed in? If they’re logged in, the user object is already available with current_user. Rather than User.find_by(:user_id).observations in the controller, I could just do current_user.observations.

However, the URL structure above seems more RESTful. If the URL were just api/observations/, that would seem to imply that the response should include all observations. But really, in the application domain there is no concept/need to return a list of all observations of all users.

Hopefully this makes sense. Thanks in advance if anyone has any thoughts!

I agree that the user_id shouldn’t be present in the URL. I don’t think having the URL api/observations for the current user is a problem – many APIs use this form.

1 Like

It is depend if current_user might need or not to access the /members resource, i.e. other members and their observations. And as far as the resources built around currently authenticated user it means that all of them already scoped to the current_user session, i.e. /api/observations is fine.

1 Like

if you have access to current_user, and you don’t forsee the need to pull anything other than the current_user why not use a collection route?

ie:

resources :users do
    collection do
        get 'index', on: :observations
    end
end

note: untested, so syntax might be off a little, but this will make it so that the parameters portion of the generated URI is missing leaving you with users/observations or something along those lines.

1 Like