Search code examples
grailsgroovygrails-orm

Need help improving how objects are saved from params in my app


So, I have a form that collects a bunch of radio selections and checkboxes and I need to build a series of objects based on what gets returned, which might look like this:

[thingid:1, 13:30,14:33, 11:26, 12:78, action:save, controller:userThing] 

One object is created from the thingid, and the integer value pairs are ids of 2 other objects that are used to create n additional objects, so right now I'm looping through the params with an each() and filtering the non integer pairs with a long if expression, and then saving the object I need :

 params.each {
     key, value ->
     if (key=="submit" | key=="action" | key=="thingid" | key=="controller"){}else{
     def prop = ThingProperty.find(){
         id == key
     }
     def level = ThingLevel.find(){
         id == value
     }

    new UserThingScore(userthing: userthing,thingproperty: prop ,thinglevel: level).save(flush:true)
             }
 }

It works, in that it creates all the necessary objects correctly, but this just seems ridiculous to me, and I know there must be a better way... is there someway I can group form elements so they get returned like this?:

[thingid:1, integerpairs:[13:30,14:33, 11:26, 12:78],action:save,controller:userThing]

Solution

  • An alternative might be:

    def userThingList = params.keySet().grep( Integer ).collect { it ->
        new UserThingScore( userthing: userthing,
                            thingproperty: ThingProperty.get( it ),
                            thinglevel: ThingLevel.get( params[ it ] ) )
    }
    
    userThingList*.save()