Search code examples
grailsgrails-controller

Grails redirect breaks params types


My Grails code has a search function that redirects to another controller action after performing a findAllBy query:

def results = Foo.findAllByBar(baz)
redirect(action: "result", params: [results: results])

findAllByBar returns an ArrayList with models, as expected, but after the redirect the receiving action gets a String array. Worse, when there is only one result it doesn't even get an array, it just gets a String.

Given that I have to iterate through the results in the receiving view, doing it on a string will meticulously print every letter individually. We can all agree that that's probably not the ideal behaviour.


Solution

  • A redirect results in a new GET request with the parameters in the querystring, e.g. /controller/result?foo=bar&baz=123 - you can't put objects there since it's just a string.

    You could put the ids of the objects in the params and load them in the result action:

    def action1 = {
       def results = Foo.findAllByBar(baz)
       redirect(action: "result", params: [resultIds: results.id.join(',')])
    }
    
    def result = {
       def resultIds = params.resultIds.split(',')*.toLong()
       def results = Foo.getAll(resultIds)
    }
    

    or put them in Flash scope:

    def action1 = {
       flash.results = Foo.findAllByBar(baz)
       redirect(action: "result")
    }
    
    def result = {
       def results = flash.results
    }