在 rails 中使用嵌套资源时如何修改 form_with
how to modify form_with when using nested resources in rails
我正在学习使用 rails 中的嵌套资源。为了保持简单和可重现,我设置了一个非常简单的博客应用程序,其中包含两个资源 posts
和 comments
。大部分代码已经由脚手架生成。
我已经成功修改post#show
在每个post下方显示comments
,link到Add New Comment
也呈现new comment
形式.但是我无法保存评论并收到路由错误:
ActionController::RoutingError (No route matches [POST] "/posts/1/comments/new"
评论部分形式对比
original/before嵌套资源:
<%= form_with(model: comment, local: true) do |form| %>
modified/after嵌套资源:
<%= form_with(url: new_post_comment_path,
scope: :comment, local: true) do |form| %>
我已将代码推送到 github repo,有单独的分支 master
没有嵌套资源,nestedRoutes
有嵌套资源。感谢社区的帮助。
注意: 的答案对我不起作用。
看起来你传递的 url 是 new_post_comment_path
,当你可能希望你的表单进入创建路径时。根据您的路线,我认为这看起来像 post_comments_path
。
这就是您看到错误的原因,没有为 new
路径定义 POST 方法(仅 GET)。
我正在学习使用 rails 中的嵌套资源。为了保持简单和可重现,我设置了一个非常简单的博客应用程序,其中包含两个资源 posts
和 comments
。大部分代码已经由脚手架生成。
我已经成功修改post#show
在每个post下方显示comments
,link到Add New Comment
也呈现new comment
形式.但是我无法保存评论并收到路由错误:
ActionController::RoutingError (No route matches [POST] "/posts/1/comments/new"
评论部分形式对比
original/before嵌套资源:
<%= form_with(model: comment, local: true) do |form| %>
modified/after嵌套资源:
<%= form_with(url: new_post_comment_path,
scope: :comment, local: true) do |form| %>
我已将代码推送到 github repo,有单独的分支 master
没有嵌套资源,nestedRoutes
有嵌套资源。感谢社区的帮助。
注意:
看起来你传递的 url 是 new_post_comment_path
,当你可能希望你的表单进入创建路径时。根据您的路线,我认为这看起来像 post_comments_path
。
这就是您看到错误的原因,没有为 new
路径定义 POST 方法(仅 GET)。