botbot
botbot

Reputation: 7359

Basic Nested Routes (how to have nested routes and not nested routes simultaneously)

I have routes like this:

resources :users do
  resources :projects
end

I would like to be able to access routes like this:

/users/1/projects/1

and

/projects/1

Is this possible? How would I set this up? I'm having and issue in my app where we would like to have users able to see both their own projects via /users/:id/projects/:id but also on other pages we'd like to just see all the projects created, like this /projects or a project and an id, like this /projects/:id. I feel like I'm missing something, should I just get rid of the nested routes? Or can I have both.

Upvotes: 1

Views: 71

Answers (2)

Shreyas Agarwal
Shreyas Agarwal

Reputation: 1128

You can surely have both ways depending on your needs.

resources :users do
  resources :projects 
end
resources :projects

Will give you your url in /users/:user_id/projects/:id and in /projects/:id as well.

You can check in your projects controller whether the params[:user_id] exists or not and take necessary action.

Upvotes: 2

Erez Rabih
Erez Rabih

Reputation: 15788

You can have both. Just add resources :projects to your routes.rb. Then, in your ProjectsController you will have to do:

def index
  if params[:user_id]
    @projects = User.find(params[:user_id]).projects
  else
    @projects = current_user.projects
  end
end

I'm assuming your authentication system provides with current_user method for your controllers (as most of them do)

Upvotes: 2

Related Questions