Emu
Emu

Reputation: 5905

Rails 5 nested routes

I've three models Project, Card and Task.

project has_many :cards

card has_many :tasks

I've defined the route for building cards like following:

resources :projects, except: [:new, :edit, :show] do
    resources :cards do
      resources :tasks
    end
end

It'll create path for cards as: projects/:project_id/cards/

It'll create path for tasks as: projects/:project_id/cards/:card_id/tasks

What I need is: Card routes should be nested to Project. (which I currently have) and Task routes should nested to only Card like /cards/:card_id/tasks (which I need).

How can I achieve that?

Thanks in advance!

Upvotes: 1

Views: 55

Answers (2)

Pengcheng Zhou
Pengcheng Zhou

Reputation: 172

resources :projects, except: [:new, :edit, :show] do
    resources :cards
end
resources :cards do
    resources :tasks
end

This is what you are looking for

Upvotes: 1

ray
ray

Reputation: 5552

You can just do,

resources :projects, except: [:new, :edit, :show] do
    resources :cards
end

And further try with defining each route for task by,

get '/cards/:card_id/tasks', to: 'tasks#index'

I did not test but should work, Sad is you have to define it for each specific route.

Upvotes: 0

Related Questions