grails - 将购物车对象链接到用户对象

标签 grails

美好的一天。我是grails的新手,我必须设计一个音乐购物类型的应用程序。我有一个Cart域和一个User域,我想做的是在创建新的User对象时也要创建一个新的Cart对象,该对象也链接到User中的所说User对象。我正在使用静态脚手架,因此我想在“用户/保存”操作中执行此操作。这是我的代码:

class Cart {
    String item
    Integer quantity
    BigDecimal price
    String type
    Integer typeId
    User user
    static constraints = {
        type nullable:false, blank:false, inList:["Album", "Song", "Empty"]
        typeId nullable:false, blank:false
    }
}

class User {
    String username
    String password
    String fName
    String lName
    String email
    static constraints = {
        username(nullable : false, blank : false, minSize : 1)
        password(nullable : false, blank : false, minSize : 1)
        fName(nullable : false, blank : false, minSize : 1)
        lName(nullable : false, blank : false, minSize : 1)
        email(nullable : false, blank : false, email : true)
    }
}

class UserController {
    //static scaffolded code (index, show, create, etc.)
    @Transactional
    def save(User userInstance){     //This whole method is also generated with scaffolding 
        if (userInstance == null) {
            notFound()
            return
        }

        if (userInstance.hasErrors()) {
            respond userInstance.errors, view: 'create'
            return
        }

        userInstance.save flush: true

        //This is what I've been trying to do but it doesn't work and I don't know why :(
        def myCart = new Cart(user:userInstance, item:'empty item', quantity:0, price:0, total:0, type:'Empty', typeId:0).save(flush:true)

        //Rest of the generated code
    }
    //More generated code
}

任何帮助,将不胜感激。谢谢!

最佳答案

Cart类中有2个错误。
首先:将typeID更新为typeId
第二:类型应为String,而不是BigDecimal

关于grails - 将购物车对象链接到用户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36005241/

相关文章:

java - Grails 3.2.4 拒绝保存域实例 : java. lang.IllegalArgumentException:对象不是声明类的实例

grails - 每个请求只能调用一次 ServletFileUpload.parseRequest() 吗?

grails - 如何导出Config.groovy中相对目录的物理路径?

mysql - 查询 mysql 导致错误 : Illegal mix of collations (latin1_swedish_ci, IMPLICIT)

groovy - 用于定义关系的常规静态 block

grails - 如何通过Grails中的所有参数调用另一个 Controller (以相同的形式更新关联的表)

grails - grails redirect(action :'index')重定向以显示操作

grails - Grails升级2.4.0-> 2.5.4缓存插件问题

grails - 另一个grails urlmapping问题

javascript - AngularJs中如何实现数据库变化后 View 自动更新?