我正在做一个阅读故事的网站。我的目标是将故事的内容保存到几页中以获得列表,然后轻松地对其进行分页;我做了以下事情:
在域中我创建了两个域,Story
:
class Story {
String title
List pages
static hasMany=[users:User,pages:Page]
static belongsTo = [User]
static mapping={
users lazy:false
pages lazy:false
}
}
和页面
:
class Page {
String Content
Story story
static belongsTo = Story
static constraints = {
content(blank:false,size:3..300000)
}
}
Controller 保存
操作是:
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])
}
}
关于for 循环中的 Grails addTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3483664/