4

update/replace各またはinsert検証が失敗したときにメッセージを返す前にカスタム検証(ある種のフック)を実行する方法はありますか? でできるのと同じようにActiveModel

検証関数を書くこともできますが、このモデルを更新または挿入したすべての場所を書き直す必要があります。

4

1 に答える 1

1

私の知る限り、永続性には検証用の組み込みフックがありません。これは私が使用するものです(yesodのi18nと組み合わせて):

-- | Represents an entity that has validation logic
class Validatable e where

    -- | A set of validations and error messages for a
    --   given entity.
    validations :: e -> [(Bool, AppMessage)]
    validations _ = []

    -- | Validate an entity and respond with a Bool wrapped in
    --   a writer with potential error messages. By default this
    --   makes use of @validations e@
    validate :: e -> (Bool, [AppMessage])
    validate e = runWriter $ foldM folder True $ validations e
      where
        folder a (v, m) | v = return $ a && True
                        | otherwise = tell [m] >> return False

検証を定義します。

instance Validatable Stock where
    validations e = [ ((0<) . stockInventory $ e, MsgPurchaseErrorInventoryNegative)
                    , ((0<) . unMoney . stockPrice $ e, MsgPurchaseErrorPriceNegative)
                    , (maybe True ((0<) . unMoney) . stockCostPrice $ e, MsgPurchaseErrorCostPriceNegative)
                    , ((2<=) . length . stockName $ e, MsgPurchaseErrorNameTooShort)
                    ]

そして、あなたのハンドラーで:

let (isvalid, errors) = validate s
unless isvalid $ invalidArgsI errors
于 2015-06-12T06:27:31.840 に答える