【问题标题】:Yesod - Form with foreign keyYesod - 带有外键的表单
【发布时间】:2017-09-06 15:14:12
【问题描述】:

我正在使用 Yesod 开发我的第一个应用程序,并且我正在创建一些 CRUD api 来启动。

我有一个看起来像的模型

User json
    ...

Activity json
    userId UserId
    ...

其中userId 是外键。

我需要创建一个端点才能创建一个新的 Activity,并且客户端需要能够指定 userId

为此,我使用了类似的表单

postCreateActivityR :: Hadler Value
postCreateActivityR = do
    activity <- runInputPost $ Activity
        <$> ...
        <*> ireq textField "userId"
    ...

这样做会出现如下错误:

Couldn't match type ‘Text’ with ‘Key User’ expected type: FormInput (HandlerT App IO) (Key User)

有解决这个问题的标准方法吗?

【问题讨论】:

标签: haskell yesod yesod-forms


【解决方案1】:

如果您使用 SQL 后端,toSqlKey 位于 Database.Persist.Sql 模块中。既然给你Text,你首先需要用Data.Text.Read把它转换成Int64

【讨论】:

    【解决方案2】:

    为了记录,我最后是这样解决的

    我必须创建一个新字段

    userIdField :: (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m UserId
    userIdField = Field
        { fieldParse = parseHelper $ \s ->
            case signed decimal s of
                Right (a, "") -> Right $ toSqlKey a
                _ -> Left $ MsgInvalidInteger s
        , fieldView = \_ _ _ _ _ -> ""
        , fieldEnctype = UrlEncoded
        }
    

    然后像这样使用它

    <*> ireq userIdField "userId"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      相关资源
      最近更新 更多