Best practices for grails index page

grailsindexingmodel

What is the right way to populate the model for the index page in a grails app? There is no IndexController by default, is there some other mechanism for getting lists of this and that into the model?

Best Solution

I won't claim that this is the right way, but it is one way to start things off. It doesn't take much to have a controller be the default. Add a mapping to UrlMappings.groovy:

class UrlMappings {
    static mappings = {
      "/$controller/$action?/$id?"{
            constraints {
                // apply constraints here
            }
        }
      "500"(view:'/error')
     "/"
        {
            controller = "quote"
        }
    }
}

Then add an index action to the now default controller:

class QuoteController {

    def index = {
        ...
    }
}

If what you want to load is already part of another action simply redirect:

def index = {
    redirect(action: random)
}

Or to really get some reuse going, put the logic in a service:

class QuoteController {

    def quoteService

    def index = {
        redirect(action: random)
    }

    def random = {
        def randomQuote = quoteService.getRandomQuote()
        [ quote : randomQuote ]
    }
}