我在使用grails创建Web论坛时遇到了一些问题。在我的Controller中,我需要为网站工作创建一个标准主题,我正在使用教程代码。所以我的问题是:如何为此代码工作创建标准主题?
我需要创建的部分位于第11行。
控制器:
class ForumController {
def springSecurityService
def home() {
[sections:Section.listOrderByTitle()]
}
def topic(long topicId) {
Topic topic = Topic.get(topicId)
if (topic == null){
}
params.max = 10
params.sort = 'createDate'
params.order = 'desc'
[threads:DiscussionThread.findAllByTopic(topic, params),
numberOfThreads:DiscussionThread.countByTopic(topic), topic:topic]
}
def thread(long threadId) {
DiscussionThread thread = DiscussionThread.get(threadId)
params.max = 10
params.sort = 'createDate'
params.order = 'asc'
[comments:Comment.findAllByThread(thread, params),
numberOfComments:Comment.countByThread(thread), thread:thread]
}
@Secured(['ROLE_USER'])
def postReply(long threadId, String body) {
def offset = params.offset
if (body != null && body.trim().length() > 0) {
DiscussionThread thread = DiscussionThread.get(threadId)
def commentBy = springSecurityService.currentUser
new Comment(thread:thread, commentBy:commentBy, body:body).save()
// go to last page so user can view his comment
def numberOfComments = Comment.countByThread(thread)
def lastPageCount = numberOfComments % 10 == 0 ? 10 : numberOfComments % 10
offset = numberOfComments - lastPageCount
}
redirect(action:'thread', params:[threadId:threadId, offset:offset])
}
}
答案 0 :(得分:1)
您的问题目前尚不清楚,但如果您问如何创建Topic
域类的初始实例(以便可以在thread
操作中加载),则可以执行此操作所以在Bootstrap.groovy
:
def init = { servletContext ->
if(!Topic.list()) { //if there are no Topics in the database...
new Topic(/*whatever properties you need to set*/).save(flush: true)
}
答案 1 :(得分:0)
目前,您首先尝试查找与提供的topicId对应的Topic域类的实例,然后检查主题是否为null。
这是一个问题,好像topicId为null,查找将失败并抛出空指针异常。
要解决此问题,您只需将查找包装在if-null检查中,如下所示,以确保您实际拥有有效的topicId。
您的另一个问题(如何实际设置默认值)更直观一些。如果没有找到主题,只需使用默认构造函数创建一个主题,或者为构造函数提供键:值对。 [参见下面的代码示例]。有关Grails对象关系映射系统的更多信息,请查看their documentation。
def topic(long topicId) {
Topic topic
/* If you have a valid topicId perform a lookup. */
if (topicId != null){
topic = Topic.get(topicId)
}
/* If the topic hasn't been set correctly, create one with default values. */
if (topic == null) {
topic = new Topic()
/* You may want to have a look at the grails docs to see how this works. */
toipic = new Topic(name: "Default", priority: "Highest")
}
params.max = 10
params.sort = 'createDate'
params.order = 'desc'
[threads:DiscussionThread.findAllByTopic(topic, params),
numberOfThreads:DiscussionThread.countByTopic(topic), topic:topic]
}