Catfish
Catfish

Reputation: 19324

Rails trying to create nested routes

Ok i'm shooting to have a url like this /applications/:application_id/jobseekers/new. I know if i generate 2 scaffolds (applications and jobseekers) i could make the routes work by doing this:

resources :applications do
  resources :jobseekers
end

but i don't need a full scaffold for jobseekers. I only need a new and create method.

How can i write my routes so that the jobseekers#new and jobseekers#create methods work?

I tried

resources :applications do 
    get '/applications/:application_id/jobseekers/new', :to => 'jobseekers#new', :as => :new_application_jobseeker
    post '/applications/:application_id/jobseekers', :to => 'jobseekers#create'
  end

but it gives me this error:

No route matches [GET] "/applications/3/jobseekers/new"

when hitting this url:

localhost:3000/applications/3/jobseekers/new

Upvotes: 1

Views: 130

Answers (3)

Chris Salzberg
Chris Salzberg

Reputation: 27384

The problem in your routes is that your are including the full path ('/applications/:application_id/jobseekers/new') inside a nested route. Instead, you need to put your get and post calls into a member block:

resources :applications do
  member do
    get "jobseekers/new", :to => 'jobseekers#new'
    post "jobseekers", :to => 'jobseekers#create'
  end
end

By doing this, Rails will match /applications/:id/ part will be prepended to "jobseekers/new" to get the full route, which you can see if you call rake routes:

new_application_jobseeker_application GET    /applications/:id/jobseekers/new(.:format) jobseekers#new
               jobseekers_application POST   /applications/:id/jobseekers(.:format)     jobseekers#create

Alternatively, you can define a nested resource and include only the new and create actions with the only option:

resources :applications do
  resources :jobseekers, :only=> [:new, :create]
end

Note that the path helpers will be slightly different in this case, and will use application_id rather than id for the id of the application:

   application_jobseekers POST   /applications/:application_id/jobseekers(.:format)     jobseekers#create
new_application_jobseeker GET    /applications/:application_id/jobseekers/new(.:format) jobseekers#new

Upvotes: 4

Sam Peacey
Sam Peacey

Reputation: 6034

You can specify the actions you want as follows:

resources :applications do
  resources :jobseekers, :only=> [:new, :create]
end

Upvotes: 5

t56k
t56k

Reputation: 7011

Just create the table with a migration, and a model and a controller manually, then add only the methods you want.

rails g model jobseekers

etc.

Upvotes: 0

Related Questions