与:id的rails路由不起作用 [英] rails routes with :id not working
问题描述
我有一个名为Schedule的模型,该模型属于一个项目。一个项目有一个时间表。我正在尝试遵循CRUD约定,但是有些困难。我有一个页面,其中列出了所有项目,并且每个项目旁边都有一个链接来创建时间表。我在路由文件中从以下内容开始:
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
这是问题所在。在新时间表页面的网址中,需要有一个:id来引用该时间表所属的项目,这样,在创建时间表时它将属于适当的项目。我不知道使用资源的方法,因此我将路线代码更改为:
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.
更新:
我还尝试将路线更改为以下内容:
I also tried changing my routes to the following:
resources :projects do
resources :schedules
end
这使新日程表的URL形式为:
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
,并产生以下错误:
undefined method `schedules_path'
有什么想法吗?
推荐答案
由于您具有嵌套的资源/路由,因此需要传递一个包含 @schedule
实例变量的数组(新的 Schedule
对象)以及@project实例变量(保存父 Project
对象)到 form_for
:
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 :
您的命名匹配路线(即 match'schedules / new /:id'
)路由失败,因为 schedules#new
控制器操作是RESTful的,因此不会不是接受 id
参数。但是,您在更新中正确地修改了路线–通过嵌套资源,确实可以在路线中表示项目/进度表之间的父子关联。
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.
结果路径– / projects /:project_id / schedules / new
–要求将一组对象传递给您的 form_for
助手。第一个必须是现有的 Project
对象(从而满足:project_id
参数),第二个必须是新的 Schedule
对象(根据定义,该对象尚未分配 id
属性)。
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).
这篇关于与:id的rails路由不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!