0

我正在布法罗建立一个博客网站,但遇到了一些问题。我有以下路线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

4

1 回答 1

0

它看起来像一个路由问题。我偶然发现了这种问题。这与路线声明的顺序有关。路由器是顺序敏感的;它将路由到第一个匹配的声明......也许在你的情况下,匹配的第一个路由是“/”我不是 100% 确定,但尝试相反的方式 ex :

blogGroup.GET("/post/{slug}", b.Show)

blogGroup.GET("/post/{slug}/edit", b.Edit)

blogGroup.GET("/", b.List) blogGroup.GET("/new", b.New)

于 2019-03-14T17:36:09.403 回答