【问题标题】:Grails Controllers adding instancesGrails 控制器添加实例
【发布时间】:2010-09-21 21:50:51
【问题描述】:

好的,我之前问过一个问题,但不太确定。所以我继续等到现在再问。

主要问题

如何通过控制器添加域的新实例?我创建了一个名为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)
    }
}

【问题讨论】:

    标签: grails controller dns show add


    【解决方案1】:

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

    【讨论】:

    • 感谢您指出这一点,但这是我尝试的第一件事,并没有改变结果。
    • 好吧,除非您调用该方法,否则它们肯定不会保存。你一定也有其他问题。检查 save() 的返回值是否不为空。如果是,则有一个验证错误阻止它们持续存在
    • 谢谢,我会检查并回复。
    • 我最终重新开始了我的项目。我相信,由于我的项目处于生产模式,它相信一些旧变量仍然应该添加到表中。不知道为什么。无论如何,我创建了一个新项目并将其保持在测试模式,直到完全准备好。谢谢你的帮助:)
    【解决方案2】:

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

    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]
    

    【讨论】:

    • 我继续并更改了我的收集操作,以使用我的 _athor = new Author("$abc.author") 复制您在上面所做的操作,但它仍然没有添加它们。它实际上仍然产生了和以前一样的信息。另外,您为什么希望在保存操作中看到这一点? (我只是让它生成)
    • 我说了一些“像”!,您在这里没有提供足够的代码来提供完整的解决方案......您还没有展示作者对象的外观?您还没有说明异常是什么,如果有的话?
    • 也不例外。我将发布 Author 对象的样子。我很抱歉 Aaron,我之前没有处理过生成的视图,我认为做这样的事情与我读过的教程非常相似。我没有质疑你的工作,只是想知道你为什么会做这样的事情:) 起初我创建的 grails 应用程序根本没有数据库,现在我想实现它并遇到了上述情况。 在原始问题中发布作者对象
    • return 语句是我在“创建”操作中看到的。我认为如果我使用的是具有相同代码的 gsp,则需要这样做。我没有做像你编辑的代码这样的事情。我在 bookInstance 和 bookListInstance 上尝试了一个 println 并且两者都是空的:/ 我想要做的就是让数据库使用在使用收集操作时从文件中提取的数据更新表。也许还有另一种/更简单的方法可以做到这一点?
    • 感谢您的帮助亚伦。我相信我弄清楚了这个问题。还要感谢您花时间整理示例代码,因为它帮助我理解了更多内容
    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多