rails routes with :id not working

邮差的信 提交于 2019-12-24 14:22:00

问题


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?


回答1:


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).




回答2:


if you are using custom views, such shedules/get, you should add line get "shedules/get" in config/routes.rb file




回答3:


If you nest the resources that way, all schedule method helpers will need to be preceded with project or projects. For example, project_schedules_path. That's why you're getting that error. You have a link using the wrong path helper.

See http://guides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects



来源:https://stackoverflow.com/questions/20133036/rails-routes-with-id-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!