【发布时间】:2018-09-17 20:54:27
【问题描述】:
(This was asked before but it has no answers).
我在数据库中有一个国家/地区列表:
share [mkPersist sqlSettings] [persistLowerCase|
Country
name Text
UniqueCountryName name
deriving Show
|]
我可以显示一个表格来选择其中一个:
countries = do
rows <- runDB $ selectList [] [Asc CountryName]
optionsPairs $ map (\ r -> (countryName $ entityVal r, entityKey r)) rows
surveyForm :: Html -> MForm Handler (FormResult SurveyAnswerSet, Widget)
surveyForm extra = do
(countryR, countryV) <- mreq (selectField countries) "" Nothing
我知道我应该将最后一行中的Nothing 替换为所需的默认值,但我仍然不知道该怎么做。查看mreq 和optionsPairs 签名,我的想法是,在这种情况下,我应该提供带有默认国家/地区的Maybe Option,但我的尝试引发了很多类型错误,以至于我可能离正确答案还很远。
Yesod 书中有一个示例,使用似乎比我试图实现的更简单,所以我不知道如何推断它。
顺便说一下,我是从数据库中获取默认国家/地区的,所以我不需要硬编码其内部 ID:
defaultCountry = do
row <- runDB $ getBy $ UniqueCountryName $ countryName "United States"
(countryName $ entityVal row, entityKey row)
当我将它作为参数传递给 mreq 时,我收到以下错误:
无法将类型“(,) Text”与“HandlerFor site”匹配 预期类型:HandlerFor 站点(关键记录) 实际类型:(文本,关键记录)
这是defaultContry 函数 ((countryName $ entityVal row, entityKey row)) 的最后一行。我知道我应该从这对中取出 Key record 并将其返回到 HandlerFor site 但同时我也得到:
无法匹配预期类型“可能(关键国家)” 实际类型为“HandlerFor site0 (Key record0)”
在(countryR, countryV) <- mreq (selectField countries) "" defaultCountry 行中。我将此解释为“您传递给我一个HandlerFor site0 (Key record0),但我只接受Maybe (Key Country),这似乎与第一个错误相冲突......
在(countryName $ entityVal row, entityKey row) 行我还看到:
无法匹配预期类型“实体国家/地区” 实际类型为“可能(实体国家)”
在row 参数中。我知道我应该从Maybe 中提取Entity Country,但是如果我模式匹配并仅传递Entity Country(即:Just (Entity countryId country) -> (countryName $ entityVal (Entity countryId country), entityKey (Entity countryId country)),我仍然会收到第一个错误。
提前致谢。
【问题讨论】:
-
mreq 中的默认值不是 OptionPair 的默认值,而是填充 countryR (或 countryV ,它曾经包含该值)的默认值。在您的情况下,它可能是 Text 或 CountryKey。
-
这里的类型有点混乱——你认为你可以注释
defaultCountry和countries吗?否则,我看不出你为什么不做(name, key) <- defaultCountry; (countryR, countryV) <- mreq (selectField countries) "" (Just key)。 -
谢谢大家,我用 GHC 错误更新了我的问题。它们包括预期和提供的类型。我试图跟随他们,但我迷路了,因为他们中的两个似乎发生了冲突。
标签: haskell yesod yesod-forms