Search code examples
grailsgrails-orm

Relationship Many-To-One how to save


I've searched on google and mostly of examples didn't helped or I'm doing wrong what I want. So I quite don't understand how GORM saves in this type of relationship, how I can save new event that is related on the user? the addToEvent doesn't work.

class User{
Long id
String name
Long codeUser
StatusType statusType
static hasMany = [event: Event]
static constraints = {
    statusType(nullable: true)
    name(nullable: true)
}
class Event{
Long id
String name
String startDate
String description
static belongsTo = [user:User]
static constraints = {
    name(nullable: true)
    startDate(nullable: true)
    description(nullable: true)
}

def createEvent(){
    def data = JSON.parse(params.data)
    def user = User.findByCodeUser(data.codeUser)
    def event = new Event(name: data.name, startDate: data.start_time, description: data.description)
    //removed the user: user
    user.addToEvent(event)
    user.save(flush: true)
}

The error is this: Message: No signature of method: java.util.ArrayList.addToEvent() is applicable for argument types: (project.web.Event) values: [project.web.Event : (unsaved)]


Solution

  • 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]