As outlined in the Grails documentation you need to use the addTo* method to save the relationship correctly through GORM.
class User{
...//attributes
Long codeUser
static hasMany = [event: Event]
}
class Event{
...//attributes
Long codeEvent
static belongsTo = [user:User]
}
def user = User.findByCodeUser(params.codeUser)
def event = new Event(codeEvent: params.codeEvent)
user.addToEvent(event)
user.save(flush: true)
Notice that you don't have to set the User
property of the Event
and saving the User
will also save the Event
.
Finally, as a style guide you typically want to name your collections in the plural form.
static hasMany = [events: Event]