Search code examples
ruby-on-railsroutesruby-on-rails-4rails-routingactiveresource

rails routes with :id not working


I have a model called Schedule that belongs_to a project. A project has_one schedule. I am trying to follow CRUD conventions but having some difficult. I have a page that lists all the projects and has a link next to each project to create a schedule. I started out with the following in my route file:

resources :schedules

Here's the problem. In the url of the 'new schedule' page there needs to be an :id that refers to the project that the schedule belongs to, that way when the schedule is created it will belong to the proper project. I don't know of a way to do that with resources, so I changed my routes code to:

match 'schedules/new/:id', to: 'schedules#new', as: :new_schedule, via: [:get, :post]
resources :schedules, except: [:new, :create]

For some reason, this page is blank. It's just white. How do I fix my routes? Thanks.

UPDATE:

I also tried changing my routes to the following:

resources :projects do
    resources :schedules
end

This makes the url for a new schedule in the form of:

/projects/:project_id/schedules/new(.:format)

I think this is how it should be done, however, the form for new schedules is written as

form_for @schedule

and that produces the following error:

undefined method `schedules_path'

Any ideas?


Solution

  • Since you have a nested resource/route, you need to pass an array containing both the @schedule instance variable (holding the new Schedule object) along with the @project instance variable (holding the parent Project object) to your form_for:

    form_for [@project, @schedule]
    

    EXPLANATION:

    Your named match route (i.e., match 'schedules/new/:id') fails to route because the schedules#new controller action is RESTful and thus does not accept an id parameter. However, you correctly amended your route in your update – the parent-child association between projects/schedules should indeed be represented in your routes by nesting your resources.

    The resulting path – /projects/:project_id/schedules/new – requires that an array of objects be passed to your form_for helper. The first must be an existing Project object (thus satisfying the :project_id parameter) and the second must be a new Schedule object (which, by definition, will not yet have an id attribute assigned).