You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IHP博客教程报错:NewView的comment字段未初始化求解

问题:IHP创建Post时NewView缺少comment字段初始化错误

问题描述

我正在学习IHP博客教程,但遇到了如下错误,我是Haskell新手,询问ChatGPT也未解决。我猜测创建Post时需要初始化空Comment,因为NewView定义包含该字段,特请教解决方法。

报错信息

Web/Controller/Posts.hs:47:37
    * Fields of `NewView' not initialised:
        comment :: Comment
    * In the first argument of `render', namely `NewView {..}'
      In the expression: render NewView {..}
      In a case alternative: Left post -> render NewView {..}
   |
47 |                 Left post -> render NewView { .. }
   |                                     ^^^^^^^^^^^^^^

相关源代码

Web/Controller/Posts.hs

action CreatePostAction = do
    let post = newRecord @Post
    post
        |> buildPost
        |> ifValid \case
            Left post -> render NewView { .. }
            Right post -> do
                post <- post |> createRecord
                setSuccessMessage "Post created"
                redirectTo PostsAction

Web/View/Comments/New.hs

data NewView = NewView
    { comment :: Comment
    , post :: Post
    }

解决方案

你的猜测完全正确——NewView定义明确要求必须传入comment和post两个字段,但当前代码里只提供了post,所以编译器抛出未初始化字段的错误。

只需在CreatePostAction中新增一行初始化空Comment记录的代码,即可解决问题:

修改后的Web/Controller/Posts.hs代码:

action CreatePostAction = do
    let post = newRecord @Post
        comment = newRecord @Comment  -- 初始化空的Comment记录
    post
        |> buildPost
        |> ifValid \case
            Left post -> render NewView { .. }  -- 现在{..}会自动填充post和comment字段
            Right post -> do
                post <- post |> createRecord
                setSuccessMessage "Post created"
                redirectTo PostsAction

说明

  • newRecord @Comment会创建一个默认初始化的空Comment实例,刚好满足NewView对comment字段的类型要求
  • Haskell的记录语法{..}会自动将当前作用域中的post和comment变量对应填充到NewView的同名字段中,这样就完整满足了NewView的字段初始化要求,编译器错误会消失

内容的提问来源于stack exchange,提问作者Geoff Langenderfer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:07:12