Reputation: 601
I'm working on a grails app that has a one to many relationship between User and Tasks. When I create a task, I either get an error:
Property [user] of class [class app.Task] cannot be null or failed to lazily initialize a collection of role: app.User.tasks, no session or session was closed
I am able to successfully save a task to the user in the bootstrap, but am unable to do so in the TaskController.
I'm pretty sure that I've got one line of code wrong and am wondering what it is. My code is below.
def save() {
def taskInstance = new Task(params)
println "attempting to save ${session.user.toString()}"
println "adding task to user"
def tasks = session.user.getTasks()
println "got tasks"
println "adding task to user"
session.user.addToTasks(taskInstance) <--error here
println "task added successfully"
if (!taskInstance.save(flush:true)) {
println "task saved and flushed"
render (view: "create", model: [taskInstance: taskInstance])
return
}
flash.message = message(code:'default.created.message',
args: [message(code: 'task.label', default: "Task"), taskInstance.id])
redirect(action:"show", id:taskInstance.id)
}
Upvotes: 0
Views: 186
Reputation: 35904
Working directly with an object stored in the Http Session is generally not a good idea. What I would do is the following:
def save() {
def user = User.get(session.user.id)
// or
def user = session.user.merge() // not 100% this would work right
... all your other code
}
Reason is that the User is detached from the hibernate session and you need a hibernate session for all the persistence and GORM goodness to work correctly.
Upvotes: 1