我正在布法罗建立一个博客网站,但遇到了一些问题。我有以下路线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 并包含正确的正文?我已经尝试将 设置为<%= form_for(blog, {action: blogPath(), method: "POST"}) { %>
,<%= form_for(blog, {action: blogPostPath(), method: "POST"}) { %>
但是new.html
在我需要 slug 时出现错误localhost:3000/blog/new
。