我正在用Buffalo建立一个博客网站,我遇到了一个小问题。我在app.go中有以下路由
b := BlogsResource{}
blogGroup := app.Group("/blog")
blogGroup.GET("/", b.List)
blogGroup.GET("/new", b.New)
blogGroup.GET("/post/{slug}", b.Show)
blogGroup.GET("/post/{slug}/edit", b.Edit)
blogGroup.POST("/", b.Create)
blogGroup.PUT("/post/{slug}", b.Update)
blogGroup.DELETE("/post/{slug}", b.Destroy)
blogGroup.Middleware.Skip(Authorize, b.List, b.Show)我的blogs.go资源创建方法如下所示:
func (v BlogsResource) Create(c buffalo.Context) error {
// Allocate an empty Blog
blog := &models.Blog{}
// Bind blog to the html form elements
if err := c.Bind(blog); err != nil {
return errors.WithStack(err)
}
// Get the DB connection from the context and validate it
tx := c.Value("tx").(*pop.Connection)
verrs, err := blog.Create(tx)
if err != nil {
return errors.WithStack(err)
}
if verrs.HasAny() {
// Make the errors available inside the html template
c.Set("errors", verrs)
// Render again the new.html template that the user can
// correct the input.
return c.Render(422, r.Auto(c, blog))
}
// If there are no errors set a success message
c.Flash().Add("success", T.Translate(c, "blog.created.success"))
// and redirect to the blogs index page
return c.Redirect(302, "blogPostPath()", render.Data{"slug": blog.Slug})
}new.html如下所示:
<div class="page-header">
<h1>New Blog</h1>
</div>
<%= form_for(blog, {action: blogPath(), method: "POST"}) { %>
<%= partial("blogs/form.html") %>
<a href="<%= blogPath() %>" class="btn btn-warning" data-confirm="Are you sure?">Cancel</a>
<% } %>我遇到的问题是,当我尝试重定向时,它指向了正确的url localhost:3000/blog/post/my-blog-post-here,但正文试图使用blogs/index.html模板而不是blogs/show.html。那么,我需要做什么才能使重定向指向正确的URL并包含正确的正文?我尝试在new.html中将<%= form_for(blog, {action: blogPath(), method: "POST"}) { %>设置为<%= form_for(blog, {action: blogPostPath(), method: "POST"}) { %>,但在转到localhost:3000/blog/new时遇到需要该插件的地方出现错误。
发布于 2019-03-15 01:36:09
看起来像是路由问题。我偶然发现了这类问题。这与路由删除的顺序有关。路由器是顺序敏感的;它将路由到第一个匹配的声明...也许在您的情况下,第一个匹配的路由是"/“,我不是100%确定,但尝试另一种方式,例如:
slug(“/blogGroup.GET/{slug}”,b.Show)
slug(“/blogGroup.GET/{slug}/edit”,b.Edit)
blogGroup.GET("/",b.List) blogGroup.GET("/new",b.New)
https://stackoverflow.com/questions/55054086
复制相似问题