【发布时间】:2010-08-14 14:08:27
【问题描述】:
我正在做一个阅读故事的网站。我的目标是将故事的内容保存到几页中以获取列表,然后轻松地对其进行分页;我做了以下事情:
在域中我创建了两个域,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。我认为它会一页一页地保存页面,这样我就可以获得每个故事的页面列表。
为什么会发生这种情况,有没有比我做的更简单的方法?
感谢任何帮助。
【问题讨论】:
标签: grails