2

我想提取一个数据库字段(文本)并将其作为参数从处理程序传递给另一个函数。但是,我遇到了类型错误。完全虚构的例子,所以可能会觉得有点做作,但应该说明我遇到的问题。

Person
  name Text

Car
  personId PersonId 
  name Text
  type Text

我想获取一个 Car 实体,然后找到相应的 Person。获取他的名字,然后将其作为参数传递。就像是:

data MyD = MyD { input1 :: Int} 

entryForm :: Text -> Form MyD  -- Update: Removed the incorrect extra parameter
entryForm n1 = renderDivs $ MyD
  <$> areq intField n1 Nothing

我的 get 处理程序如下所示:

getInputR :: CarId -> Handler Html
getInputR carId = do  
  car <- runDB $ get404 carId
  pid <- carPersonId car
  name <- getPName pid
  (widget, enctype) <- generateFormPost $ entryForm name
  defaultLayout $ do
     $(widgetFile "my_template")
  where
     getPName pid = do
         person <- runDB $ get404 pid
         personName person

我收到一条错误消息:

Couldn't match expected type `HandlerT App IO t0'
       with actual type `KeyBackend
                      persistent-1.2.1:Database.Persist.Sql.Types.SqlBackend Person'
In the return type of a call of `carPersonId'
In a stmt of a 'do' block: pid <- carPersonId car

我究竟做错了什么?

谢谢!

4

1 回答 1

2

Try changing

pid <- carPersonId car
name <- getPName pid

to

name <- getPName $ carPersonId car

The value returned from your runDB call is not inside the handler monad so you don't need to use the arrow syntax to access it.

For the second error, the issue is similar: The getPName function's return type is in the Handler monad since it uses runDB, so you need to use return to put the value into the monad:

getPName pid = do
     person <- runDB $ get404 pid
     return $ personName person
于 2013-07-26T22:19:29.893 回答