Grails addTo in for循环

时间:2010-08-14 14:08:28

标签: grails

我正在做一个阅读故事的网站。我的目标是将故事内容保存到几个页面以获取列表,然后轻松地对其进行分页;我做了以下事情:

在域中我创建了两个域Story

class Story {

    String title

    List pages

    static hasMany=[users:User,pages:Page]
    static belongsTo = [User]

    static mapping={
        users lazy:false
        pages lazy:false

    }
}

Page

class Page {
    String Content
    Story story
    static belongsTo = Story
    static constraints = {
        content(blank:false,size:3..300000)
    }

}

控制器save操作是:

def save = {
    def storyInstance = new Story(params)
    def pages = new Page(params)
    String content = pages.content
    String[] contentArr = content.split("\r\n")

    int i=0

    StringBuilder page = new StringBuilder()
    for(StringBuilder line:contentArr){
        i++
        page.append(line+"\r\n")

        if(i%10==0){

               pages.content = page
               storyInstance.addToPages(pages)
               page =new StringBuilder()
        }
    }

    if (storyInstance.save(flush:true)) {
        flash.message = "${message(code: 'default.created.message', args: [message(code: 'story.label', default: 'Story'), storyInstance.id])}"
        redirect(action: "viewstory", id: storyInstance.id)
    }else {
        render(view: "create", model: [storyInstance: storyInstance])
    }
}

(我知道它看起来很乱,但它是原型)

问题在于,我等待storyInstance.addToPages(pages)每次条件为真时向页面集添加一个页面实例。但是实际发生了什么,它只给我最后一个实例page_idx。我以为它会逐页保存页面,所以我可以得到每个故事的页面列表。

为什么会发生这种情况,是否有比我更简单的方法呢?

感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

您只使用一页...正确的解决方案:

     def save = {
        def storyInstance = new Story(params)
        def i = 0

        StringBuilder page = new StringBuilder()
        for(StringBuilder line in params?.content?.split("\r\n")){
            i++
            page.append(line+"\r\n")

            if(i%10 == 0){
                   storyInstance.addToPages(new Page(content: page.toString()))
                   page = new StringBuilder()
            }
        }

    if (storyInstance.save(flush:true)) {
        flash.message = "${message(code: 'default.created.message', args: [message(code: 'story.label', default: 'Story'), storyInstance.id])}"
        redirect(action: "viewstory", id: storyInstance.id)
    }else {
        render(view: "create", model: [storyInstance: storyInstance])
    }
}