我一直在寻找这个,但在这里找到的答案最终出现在一个包含该值的列表中。我想知道是否没有另一种更直接的方法来做我需要的事情。
我有一个表格:
formReview :: UserId -> Form Review
formReview uid = renderDivs $ Review <$>
areq textField "Text" Nothing <*>
areq intField "Rating" Nothing <*>
areq (selectField films) "Film" Nothing <*>
pure uid
如您所见,我正在尝试将用户 ID 传递给表单,因为这些是要审核的字段:
Review
text Text
rating Int
film FilmId
author UserId
它需要作者的ID。我尝试这样做的方法是在 postReviewsR 上执行以下操作:
postReviewsR :: Handler Html
postReviewsR = do
uid <- lookupSession "_ID"
case uid of
Nothing -> do
defaultLayout [whamlet| <h1> User isn't logged in.|]
Just uid ->
((result, _), _) <- runFormPost $ formReview uid
case result of
FormSuccess review -> do
runDB $ insert review
defaultLayout [whamlet|
<h1> Review posted.
|]
_ -> redirect ReviewsR
它必须是 Maybe,因为理论上您可以尝试在不登录的情况下发布内容,因此 uid 可能为空。如果我尝试直接进入((result, _), _) <- runFormPost $ formReview uid它说有一个Maybe Text.
现在我的问题与其他帖子类似,就是这个错误:
• Couldn't match type ‘Text’ with ‘Key User’
Expected type: UserId
Actual type: Text
• In the first argument of ‘formReview’, namely ‘uid’
In the second argument of ‘($)’, namely ‘formReview uid’
In a stmt of a 'do' block:
((result, _), _) <- runFormPost $ formReview uid
链接帖子中的建议是用来keyToValues :: Key record -> [PersistValue]将显然只是文本的密钥转换为我需要的 UserId。对我来说似乎太笨拙了,我需要做所有这些,然后head在该列表上使用来获取其中的值,所有这些都是为了将 ID 放入表单中。必须有另一种更正确的方法,对吧?我在这里想念什么?我如何获得在那里进行评论的用户的 ID?
编辑:我应该指出我没有使用 Yesod.Auth 所以我不能使用它的功能。