Search code examples
grailsurl-mapping

How to make URL Mappings for both REST and browser based interactions


I want the following functions from my controller and each of these are supported by matching REST:

  • Create a color
  • Fetch a particular color based on id
  • Fetch all colors

I've got the following URL scheme:

    "/$controller/$action?/$id?"{
        constraints {
            // apply constraints here
        }
    }
    "/color"(controller: "color", parseRequest: true) {
       action = [GET: "list", POST: "save"]
    }
    "/color/$id" (resource: "color")

The above does not work well for both REST and browser based interactions.

http://localhost:8080/color/create ends up going to the show action instead. I expect it to go to create action which shows the form.

If I remove the last mapping "/color/$id" (resource: "color") then it works fine however, then the URL http://localhost:8080/color/7 breaks

Question

What is a right way of making all these URLs work consistently?


Solution

  • Add a constraint to the urlMapping plus make sure the default mapping is available.

    "/$controller/$action?/$id?"{
        constraints {
            // apply constraints here
        }
    }
    
    "/user/$id" (resource: "user"){
        constraints {
            id validator: {
                !(it in ['create', 'otherAction'])
            }
        }
    }
    

    Co-incidentally, a similar question was answered here.