2011-03-06 151 views
1

我在新的Grails和我需要你的幫助..Grails的一個一對多的關係

我有作者和圖書領域類:

class Author{ 

    static hasMany = [book:Book] 

    String name 
    //.... 
} 

class Book{ 

    static belongsTo = [author:Author] 

    String title 
    //.... 
} 

域類有自己的控制器,具有「新」行動,這將創建新的對象並保存在分貝。 在我的瀏覽器中輸入.../myApp/author/new?name = myName & ..., 在我的db中創建作者對象,但是當我輸入.../myApp/book/new?name = title & .. 它無法保存圖書對象,也許是因爲我還沒有得到作者對象...

在這種情況下我該怎麼辦? 如果有人知道解決方案,請幫助...

回答

4

您需要傳遞您想要關聯Book實例的作者的ID。您需要加載作者,並將其與您要保存的書籍相關聯。

我很確定你不能有一個名爲'new'的控制器動作。 'new'是java/groovy中的保留關鍵字。

def blah = new Blah() 
1

當定義書belongsTo作者和作者hasMany書,書不能未經作者創建的。通常,你應該做的事情是這樣的:

  • 創建作者
  • 創建書籍
  • 加入書的作者
  • 保存作者 - 自動保存>級聯的書籍。

當我看到你描述你的問題,我覺得你應該去慢,看看在Grails的格姆(Groovy的對象關係映射)的基礎知識,您可以通過實例與「Getting started with Grails」開始,或閱讀3 post about GORM Gotchas。他們很容易理解。

0

出於測試目的,你可以將某些數據加載到引導:

class BootStrap { 
    def init = { servletContext -> 
    def writer = new Author(name:"Jane") 
    writer.save() 
    if(writer.hasErrors()){ 
     println writer.errors 
    } 
    def comic = new Book(name: "superman", Author: writer) 
    comic.save() 
    if(comic.hasErrors()){ 
     println comic.errors 
    } 
    } 
def destroy = {} 
} 

這樣,你的應用程序將有一個作者和成書於它。

另外this tutorial對我非常有幫助。