2016-04-22 50 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) 
}