Nested resources routing to same action

Hi

I’m building a job board that uses a User model and a Job model. A user has many jobs, and a job belongs to a user.

I need the board to act like this:

If a user is logged in, he can see the jobs he created at /users/:user_id/jobs. If a user is not logged in, he can see all the jobs created by all users at /jobs.

Currently I have 2 routes who route to the same index action.

config/routes.rb

resources :users do

resources :jobs, shallow: true

end

resources :jobs, only: [:index]

rake routes

user_jobs GET /users/:user_id/jobs(.:format) jobs#index

jobs GET /jobs(.:format) jobs#index

Do I need the index action to conditionally check for the params[:user_id] or is there a better way to accomplish this?

Hi

I'm building a job board that uses a User model and a Job model. A user has many jobs, and a job belongs to a user. I need the board to act like this:

If a user is logged in, he can see the jobs he created at /users/:user_id/jobs. If a user is not logged in, he can see all the jobs created by all users at /jobs.

You have not stated what a logged in user will see at /jobs and what a non-logged in user will see at /users/:user_id/jobs. Remember anyone can enter any url, and could put in an id for a different user.

Why not just have one route and decide what to show based on whether the user is logged in or not?

Colin

I would recommend un-nesting them. IMHO, nested resources only make much sense when the inner ones don't make sense outside the context of the outer ones. (Alternate viewpoints welcome!) Since you allow /jobs, that's clearly not the case.

Anyway, then you can make the "my jobs" URL something like "/jobs?posted_by=123" or even "/jobs?posted_by=me" (and interpret "me" in the controller). That could even be one of many possible job filtering params.

-Dave