成品分享

这篇文章发布完以后,想着再测试一下,别有啥问题让人笑话,结果果然有问题,修改文章分类不生效。

排查之,传参、接收参数、赋值到 article 都没问题,但还是修改不生效。

article 模型添加 BeforeSave 钩子,打印 savearticle, 参数也没问题。

有点费解,回忆了下前几步调试参数,打印 article 都有关联的修改之前 category 的完整数据,是不是这个引起的?

于是在修改文章之前,把 article 关联的 category 置空(因为 golang 没有手动删除变量的功能,只能置空),试了一下,问题解决。

app/http/controllers/articles_controller.go

// Update 文章更新
func (ac *ArticlesController) Update(w http.ResponseWriter, r *http.Request) {
    // 1. 获取 URL 参数
    id := route.GetRouteVariable("id", r)

    // 2. 读取对应的文章数据
    _article, err := article.Get(id)

    // 3. 如果出现错误
    if err != nil {
        ac.ResponseForSQLError(w, err)
    } else {
        // 4. 未出现错误

        // 检查权限
        if !policies.CanModifyArticle(_article) {
            ac.ResponseForUnauthorized(w, r)
            return
        }

        // 4.1 表单验证
        _article.Title = r.PostFormValue("title")
        _article.Body = r.PostFormValue("body")
        _article.CategoryID = types.StringToUint64(r.PostFormValue("category_id"))
        _article.Category = category.Category{}

        errors := requests.ValidateArticleForm(_article)

        if len(errors) == 0 {

            // 4.2 表单验证通过,更新数据
            rowsAffected, err := _article.Update()

            if err != nil {
                // 数据库错误
                logger.LogError(err)
                w.WriteHeader(http.StatusInternalServerError)
                fmt.Fprint(w, "500 服务器内部错误")
                return
            }

            // √ 更新成功,跳转到文章详情页
            if rowsAffected > 0 {
                showURL := route.Name2URL("articles.show", "id", id)
                http.Redirect(w, r, showURL, http.StatusFound)
            } else {
                fmt.Fprint(w, "您没有做任何更改!")
                return
            }
        } else {
            // 4.3 表单验证不通过,显示理由
            view.Render(w, view.D{
                "Article": _article,
                "Errors":  errors,
            }, "articles.edit", "articles._form_field")
        }
    }

}

分割线


跟着课程跑了一遍。

感悟

不知道怎么说。

链接

go-web-learn.toomore.us/

截图

注册

登录

首页

黑哈尔
讨论数量: 4

注册会报502,但是页面不登录时的其他功能正常。

1年前 评论
黑哈尔 (楼主) 1年前

想问问楼主:embed 打包后,运行 ./goblog 报错

2022/09/27 15:41:25 template: pattern matches no files: `resources/views/articles/index.gohtml`

反复对比 也没解决

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!