Grails:如何坚持Master Detail Relationship

时间:2013-05-29 20:03:43

标签: grails gorm master-detail

我已经构建了一个UI,允许您在同一表单上输入主记录(VocabularyTest)和一组详细记录(VocabQuestion)。我很高兴提交的数据是正确的,但是当我尝试保存主记录时,我收到以下错误

null id in vocabularytest.VocabQuestion entry 

编辑 - 完整的堆栈跟踪

null id in vocabularytest.VocabQuestion entry (don't flush the Session after an exception occurs). Stacktrace follows:
Message: null id in vocabularytest.VocabQuestion entry (don't flush the Session after an exception occurs)
    Line | Method
->>   24 | save      in vocabularytest.VocabularyController
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|    195 | doFilter  in grails.plugin.cache.web.filter.PageFragmentCachingFilter
|     63 | doFilter  in grails.plugin.cache.web.filter.AbstractFilter
|   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    722 | run       in java.lang.Thread

结束编辑

我假设这种情况正在发生,因为我的详细记录上的外键引用为空,这不会让我过度惊讶,因为我没有做任何设置。

我的控制器收到的参数如下

title: Dave New Test
testItems[0].question: Q1
testItems[0].answer: A1
testItems[1].question: Q2
testItems[1].answer: A2
testItems[2].question: Q3
testItems[2].answer: A3
create: Create

我的域对象

class VocabularyTest {

    static hasMany = [testItems: VocabQuestion] 
    static constraints = {
    }

    String title;
    List <VocabQuestion>testItems = LazyList.decorate(
                                      new ArrayList(),
                                      FactoryUtils.instantiateFactory(VocabQuestion.class));

}
class VocabQuestion {

    static constraints = {

    }
    String question
    String answer
    VocabularyTest vocabularyTest

}

我的控制器的相关方法是

def save() {
        log.debug(params)
        def vocabularyTestInstance = new VocabularyTest(params)
        if (!vocabularyTestInstance.save(flush: true)) {
            render(view: "create", model: [vocabularyTestInstance: vocabularyTestInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'vocabularyTest.label', default: 'VocabularyTest'), vocabularyTestInstance.id])
        redirect(action: "index", id: vocabularyTestInstance.id)
    }

我是否正在努力做一些GORM和Grails总是很难做的事情,或者我只是错过了一些重要的事情?

1 个答案:

答案 0 :(得分:0)

试试这个:

class VocabularyTest {

    static hasMany = [testItems: VocabQuestion] 

    static constraints = {
    }

    String title 
    List testItems
}

class VocabQuestion {

    static constraints = {

    }
    static belongsTo = [vocabularyTest: VocabularyTest]  

    String question
    String answer
}