gpt4 book ai didi

grails - 创建一个标准主题

转载 作者:行者123 更新时间:2023-12-02 15:20:53 25 4
gpt4 key购买 nike

使用grails创建网络论坛时遇到一些问题。在我的Controller中,我需要为网站工作创建一个标准主题,我使用的是教程代码。所以我的问题是:如何创建标准主题以使此代码起作用?

我需要创建的部分在第11行。

Controller :

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

最佳答案

当前,您正在尝试首先查找与提供的topicId对应的Topic域类的实例,然后检查该主题是否为空。

这是一个问题,好像topicId为null,查找将失败并抛出null指针异常。

要解决此问题,您只需将查询包装在if-null检查中,如下所示,以确保您实际上具有有效的topicId。

您的其他问题(如何实际设置默认值)更加直观。如果未找到任何主题,只需使用默认的默认构造函数创建一个主题,或向该构造函数提供key:value对。 [请参见下面的代码以获取示例]。有关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]
}

关于grails - 创建一个标准主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36795512/

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