2016-04-22 72 views
0

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

,我需要创建的部分是在第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]) 
} 
} 
+2

这是有点不清楚,你问什么。您正在创建一个网络论坛,并且不确定如何设置默认的“主题”?在这种情况下,主题究竟意味着什么?主题是简单的帖子的名称 - 还是它的一个职位类别? –

+0

是的,英语并不是我的第一语言,对此我很抱歉,但我正在尝试创建一个“Topic”域类的初始实例。 '主题'是一类帖子 –

回答

0

目前你试图首先查找与提供的topicId对应的Topic域类的实例,然后检查该主题是否为空。

这是一个问题,如果topicId为空,则查找将失败并抛出空指针异常。

要解决此问题,只需将查找包装在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] 
} 
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) 
}