I have to create a Application with Grails 4. For now, there is no database, it's all in memory.
All I want, is that a Module can hold a list of doubles which represent the grades.
The domain class Module.groovy
:
package myapp
import grails.rest.Resource
@Resource(uri='/module', formats = ['json', 'xml'])
class Module {
String title
String description
int semesterID
List<Double> grades;
double finalGrade
static constraints = {
title blank:false
description blank:false
semesterID blank:false
}
}
To develop the app, I'd like to work with a populated object. So I initialize a few in BootStrap.groovy:
class BootStrap {
def init = { servletContext ->
//Create default Modules
new Module(title: "WebeC", description: "Web Engineering", semesterID: 1).save()
new Module(title: "WebeC", description: "Web Engineering", semesterID: 2).save()
new Module(title: "ism", description: "Information Security Management", semesterID: 2).save()
}
def destroy = {
}
}
So far so good, but I fail when I try to populate the grades. Things I already tried: (all in BootStrap.groovy)
//test 1
new Module(title: "WebeC", description: "Web Engineering", semesterID: 1, grades: [4.0, 5.5, 3]).save()
//test 2
new Module(title: "WebeC", description: "Web Engineering", semesterID: 1, grades: {[4, 5, 6]}).save()
// test 3
def List<Double> temp = [4.0, 5.5, 3]
new Module(title: "WebeC", description: "Web Engineering", semesterID: 1, grades: temp).save()
The output is always the same:
[{"id":1,"title":"WebeC","semesterID":1,"grades":[],"description":"Web Engineering","finalGrade":0.0}, ...]
Is it just a syntax problem or is my whole approach wrong? Thank you very much
The answer from Andriy Budzinksyy was correct. To work with the REST Api anohter file was missing under views:
model{
Module module
}
json g.render(module, [expand: ['grades'], resolveTemplate: false])
I also slightly changed BootStrap.groovy
:
new Module(title: "WebeC", description: "Web Engineering", semesterID: 1, grades: [4.0, 5.5, 3] ).save(flush: true)