2013-07-14 35 views
0

我正在使用play framework和slick,play framework在表單驗證中使用了一個case map,但有些值我不需要驗證,因爲它們不是由用戶輸入的,例如, ID &完成的日期在後端提供。如何結合類案件?

到底我想有一個像這樣的類案例,以提供給Slick並與我的表一起使用。

case class Order(id: Long, order: String, date: Date) 

對於Play的表單驗證我會提供一個單獨的案例類:

case Class inputableOrder(order: String) 

我可以再創建Order類將抓住從inputableOrder變量並將其添加Order類?

case class Order(id: Long, date: Date) // <- some way to add the variable from inputableOrder? 

我只是想避免重複,但我仍然需要兩個不同的case類(一個用於表單驗證,另一個用於與數據庫的工作)。

有沒有辦法修改現有的案例類,刪除變量或修改變量類型?

+0

我認爲你的意思是「變量」,「字段」,「屬性」,「參數」或「參數」使用「類型」這個詞。在你的第一個例子中,Order,Long,String和Date是類型,id,order和date是變量名。 – Tim

+0

@Tim我主要擔心參數的類型,因爲我無法接收復選框作爲列表(即使我爲每個和插入Int),因爲案例類變量類型是Int和Play表單驗證將只接受作爲Int的帖子,除非我使用與Slick使用的Type不同的Type類。 – John

回答

4

我覺得你有幾種選擇在這裏:

  1. InputableOrderOrder部分:

    case class InputableOrder(order: String) // ... 
    case class Order(input: InputableOrder, id: Long, date: Date) // .. 
    

    這可能是最地道的解決方案。但是如果您後來認識到InputableOrder需要的東西不應該在Order中,它可能不靈活。

  2. 使Order成爲InputableOrder的一個子類。在這種情況下,有路過的時候給超參數,並且超不能是case類的一些代碼重複,所以你必須將其聲明爲普通班,並創建一個提取自己:

    class InputableOrder(val order: String) // ... 
    object InputableOrder { 
        def unapply(o: InputableOrder): Option[String] = Some(o.order); 
        // if you have more than one constructor arguments, return 
        // a tuple like Option[(String,String)] etc. 
    } 
    
    case class Order(override val order: String, id: Long, date: Date) 
        extends InputableOrder(order) // ... 
    

    再次,與之前的觀點相同的問題會出現。

  3. 使類不同並創建輔助方法來在它們之間進行轉換。選擇取決於你的設計,但我覺得這個解決方案是最靈活:

    case class InputableOrder(order: String); 
    case class Order(order: String, id: Long, date: java.util.Date) { 
        // An additional constructor to use when converting from Inputable: 
        def this(other: InputableOrder, id: Long, date: java.util.Date) = 
        this(other.order, id, date); 
        // Update this instance with `other`: 
        def this(that: Order, other: InputableOrder) = 
        this(other, that.id, that.date); 
    
        def toInput = InputableOrder(order); 
    } 
    

    這樣,你可以通過提供丟失的字段,反之亦然創建一個InputableOrderOrder。您需要編寫一次這些輔助方法/構造函數,但使用它們非常簡單。

    您還可以使用隱式的方法,如

    implicit def toInput(other: InputableOrder): Order = other.toInput; 
    

    ,使事情變得更簡單。