gpt4 book ai didi

Grails addTo 在 for 循环中

转载 作者:行者123 更新时间:2023-12-02 13:59:21 25 4
gpt4 key购买 nike

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

在域中我创建了两个域,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)
}

}

Controller 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])
}
}

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

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

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

任何帮助表示赞赏。

最佳答案

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

     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])
}
}

关于Grails addTo 在 for 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3483664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com