Search code examples
grailsgrails-2.0grails-domain-classgrails-controller

Saving related entity in grails


I have a problem with saving form values from two domain classes

One class is

 class Ip {

String inetAddress
String dns
String os



String toString(){
    "${inetAddress}"
}

Hoster hoster

static constraints = {
     ....

and the second one is just

  class Hoster {

    static HOSTER_OPTIONS = ["Name1", "Name2", "Name3"]
String name;

String toString(){
    "${name}"
}

List ips = new ArrayList()
static hasMany = [ips : Ip]

    static constraints = {
    name(unique: true, blank: false, inList: HOSTER_OPTIONS)
}

I have a Controller where I handle the data from a form

def systems = new Ip()  
systems.inetAddress = params.ip
systems.dns = params.dns
systems.os = params.os

systems.hoster.name = params.hoster
def result = systems.save(flush: true, failOnError: true)

But I didn't get it managed that the data is saved.


Solution

  • You're not associating correctly your domain classes in the controller:

    systems.hoster.name = params.hoster
    

    Instead of setting the name, you need to set the instance that exists in the database:

    systems.hoster = Hoster.findByName(params.hoster)