Search code examples
grailsgrails-orm

Unable to insert data in Bootstrap


In BootStrap, I insert data into the table when I initialize it. The result can be inserted into the data in the category table, which is always a failure in the goods table, which is why? the goods table inserted data is fail.

Below is a table corresponding to the domain

package my

class Goods {
    String title
    String description
    BigDecimal price
    String photoUrl
    Category category
}

package my

class Category {

    String categoryName

    static hasMany = [goods:Goods]

    static constraints = {
        categoryName(unique:true)
    }
}

In BootStrap, I write those:

if (category.save()) {
    println 'new category saved!'
    /*
    def allgoods = [new gdepot2.Goods(title:'Grails',price:20.0,
    description:'Grails Book...',photoUrl:''),
    new gdepot2.Goods(title:'Groovy',price:20.0,
    description:'Groovy Book...',photoUrl:'')
    ]
    allgoods*.category = category
    if(allgoods*.save()){
    println 'all goods saved!'}
    */

    def goods1 = new my.Goods(title:'Grails',price:20.0,
                              description:'Grails Book...',photoUrl:'')
    goods1.category = category
    if (goods1.save()) {
        println 'goods1 saved!'
    }
    def goods2 = new my.Goods(title:'Groovy',price:20.0,
                              description:'Groovy Book...',photoUrl:'')
    goods2.category = category
    if (goods2.save()) {
        println 'goods2 saved!'
    }
}

Solution

  • You create new Goods with null photoUrl "photoUrl:''". Define url or add constraints - photoUrl(nullable: true)