Grails 控制器添加实例

发布于 2024-09-24 20:16:40 字数 5686 浏览 1 评论 0原文

好吧,我之前问过一个问题,但不太确定。于是我就等到现在再问。

主要问题

如何通过控制器添加新的域实例?我创建了一个名为 Gather 的函数来读取包含数据的文件,然后使用特定信息创建一本新书,但它根本没有将其添加到数据库中。

我目前有一个控制器(bookController)和它的域。

我的域非常简单:

class Book {

    static belongsTo = Author

    String toString() { bookNumber }

    Author bookAuthor
    String title


    static constraints = {
        bookAuthor()
        title()

    }
}

我只是“生成”了我的视图,因此我可以进行基本的创建、编辑、列表和显示。我继续在名为“gather”的控制器中添加了自己的控制器。对于 gsp,我只是复制了“list.gsp”,因为我只想让用户在收集功能完成后查看图书列表。

这是我的控制器的样子(只是基本生成的一加收集):

package bookdemo

import bookClient

class BookController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def gather = {

        def w = new bookClient()        //bookClient will gather books from txt files
        def hosts = ["localhost"]       //host to connect to

        w.queryData(hosts)          //grab information and parse
        def abc = w.bookList            //list of books
        w.printData(abc)            //print out list of books to make sure its not null

        int numberOfBooks = abc.size()  //list size


    //create book list and return it

        numberOfBooks.times {
        def bookInstance = new Book(Author:"$abc.author", Title:"$abc.title")
            return [bookInstance: bookInstance]
        }


    //params to show once adding books

        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [bookInstanceList: book.list(params), bookInstanceTotal: book.count()]
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [bookInstanceList: book.list(params), bookInstanceTotal: book.count()]
    }

    def create = {
        def bookInstance = new Book()
        bookInstance.properties = params
        return [bookInstance: bookInstance]
    }

    def save = {
        def bookInstance = new Book(params)
        if (bookInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])}"
            redirect(action: "show", id: bookInstance.id)
        }
        else {
            render(view: "create", model: [bookInstance: bookInstance])
        }
    }

    def show = {
        def bookInstance = book.get(params.id)
        if (!bookInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
            redirect(action: "list")
        }
        else {
            [bookInstance: bookInstance]
        }
    }

    def edit = {
        def bookInstance = book.get(params.id)
        if (!bookInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [bookInstance: bookInstance]
        }
    }

    def update = {
        def bookInstance = book.get(params.id)
        if (bookInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (bookInstance.version > version) {

                    bookInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'book.label', default: 'Book')] as Object[], "Another user has updated this Book while you were editing")
                    render(view: "edit", model: [bookInstance: bookInstance])
                    return
                }
            }
             bookInstance.properties = params
            if (!bookInstance.hasErrors() && bookInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])}"
                redirect(action: "show", id: bookInstance.id)
            }
            else {
                render(view: "edit", model: [bookInstance: bookInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def bookInstance = book.get(params.id)
        if (bookInstance) {
            try {
                bookInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
            redirect(action: "list")
        }
    }
}

gsp 显示,但由于某种原因我的新书没有添加。当我添加 println 来测试信息是否在列表中时,它显示带有正确信息的打印。所以我很困惑为什么它不“创建”新的书籍实例并将其添加到数据库中。

有什么建议吗?

编辑

作者的域类:

class Author {

    static hasMany = [books:Book]

    String authorName
    String notes

    String toString() { authorName }


    static constraints = {
        machineName()
        notes(maxSize:500)
    }
}

Alright I asked a question before but wasn't quite sure about it. So I went ahead and waited till now to ask again.

Main Question

How do I add a new instance of the domain through the controller? I created a function named gather to read a file with data and then create a new Book with the specific information, however it is not adding it to the database at all.

I currently have a controller (bookController) and the domain for it.

My domain is quite simple:

class Book {

    static belongsTo = Author

    String toString() { bookNumber }

    Author bookAuthor
    String title


    static constraints = {
        bookAuthor()
        title()

    }
}

I just 'generated' my views so I have the basic create, edit, list, and show. I went ahead and added my own inside the controller called gather. For the gsp, I just copied over the 'list.gsp' as I just want the user to view the list of books once the gather function is completed.

Here is what my controller looks like (just the basic generated one plus gather):

package bookdemo

import bookClient

class BookController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def gather = {

        def w = new bookClient()        //bookClient will gather books from txt files
        def hosts = ["localhost"]       //host to connect to

        w.queryData(hosts)          //grab information and parse
        def abc = w.bookList            //list of books
        w.printData(abc)            //print out list of books to make sure its not null

        int numberOfBooks = abc.size()  //list size


    //create book list and return it

        numberOfBooks.times {
        def bookInstance = new Book(Author:"$abc.author", Title:"$abc.title")
            return [bookInstance: bookInstance]
        }


    //params to show once adding books

        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [bookInstanceList: book.list(params), bookInstanceTotal: book.count()]
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [bookInstanceList: book.list(params), bookInstanceTotal: book.count()]
    }

    def create = {
        def bookInstance = new Book()
        bookInstance.properties = params
        return [bookInstance: bookInstance]
    }

    def save = {
        def bookInstance = new Book(params)
        if (bookInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])}"
            redirect(action: "show", id: bookInstance.id)
        }
        else {
            render(view: "create", model: [bookInstance: bookInstance])
        }
    }

    def show = {
        def bookInstance = book.get(params.id)
        if (!bookInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
            redirect(action: "list")
        }
        else {
            [bookInstance: bookInstance]
        }
    }

    def edit = {
        def bookInstance = book.get(params.id)
        if (!bookInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [bookInstance: bookInstance]
        }
    }

    def update = {
        def bookInstance = book.get(params.id)
        if (bookInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (bookInstance.version > version) {

                    bookInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'book.label', default: 'Book')] as Object[], "Another user has updated this Book while you were editing")
                    render(view: "edit", model: [bookInstance: bookInstance])
                    return
                }
            }
             bookInstance.properties = params
            if (!bookInstance.hasErrors() && bookInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])}"
                redirect(action: "show", id: bookInstance.id)
            }
            else {
                render(view: "edit", model: [bookInstance: bookInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def bookInstance = book.get(params.id)
        if (bookInstance) {
            try {
                bookInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])}"
            redirect(action: "list")
        }
    }
}

The gsp shows up but for some reason my new books are not added. When I add a println in to test whether the information is in the list, it shows prints with the correct info. So I'm confused as to why it is not 'creating' the new book instance and adding it to the database.

Any suggestions?

Edit

Domain class for author:

class Author {

    static hasMany = [books:Book]

    String authorName
    String notes

    String toString() { authorName }


    static constraints = {
        machineName()
        notes(maxSize:500)
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

胡渣熟男 2024-10-01 20:16:40

您没有在任何 Book 实例上调用 .save() ...

You're not calling .save() on any of the Book instances...

烟雨扶苏 2024-10-01 20:16:40

我建议您为控制器和/或域对象编写一些单元测试。使用此代码无法成功创建您的对象

new Book(Author:"$abc.author", Title:"$abc.title")

另外,这里的 return 语句没有任何意义

    numberOfBooks.times {
    def bookInstance = new Book(Author:"$abc.author", Title:"$abc.title")
        return [bookInstance: bookInstance]
    }

它看起来像你在不了解代码用途的情况下剪切和粘贴代码。我想你想要更多这样的东西......

    // iterate through the list of books and create the object array to pass back
    def bookListInstance = []
    w.bookList.each {
        def bookInstance = new Book(Author:it.author, Title:it.title)
        bookListInstance << bookInstance
    }
    // now return the list of domain objects
    return [bookInstance: bookListInstance]

I would suggets you write some unit tests for you controller and/or domain objects. Your objects cannot be being created successfully with this code

new Book(Author:"$abc.author", Title:"$abc.title")

Also the return statement here makes no sense

    numberOfBooks.times {
    def bookInstance = new Book(Author:"$abc.author", Title:"$abc.title")
        return [bookInstance: bookInstance]
    }

It looks like you have cut and pasted code without understanding what the code is doing. I think you want something more like this...

    // iterate through the list of books and create the object array to pass back
    def bookListInstance = []
    w.bookList.each {
        def bookInstance = new Book(Author:it.author, Title:it.title)
        bookListInstance << bookInstance
    }
    // now return the list of domain objects
    return [bookInstance: bookListInstance]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文