Reputation: 1082
I am pretty new to Grails, though I do have a lot of experience developing webapplications using other mvc frameworks in different languages (Perl, Python, Ruby).
I am trying to understand the implications of CRUD in grails.
Basically Grails creates by default for a create function the following two methods:
create, which is used to display the form to create save, which is used to save the posted form
Now coming from different frameworks I am used to having just one method for create:
create, this function will display the form if the request method is GET and save the form if the request method is POST, which seems to be the prefered way of most frameworks?!?!?
Why did Grails go the route of having completely different methods for this functionality? I know I can change it by hand, but what would be the implications of doing this? What will I loose, what will I gain.
I know this is not a very specific question and I sure do not want to start a flame war, but I want to understand why to choose one way of the other ...
Thanks in advance for your ansers.
Upvotes: 3
Views: 5717
Reputation: 4459
When you generate a controller, it uses some default templates with {index, list, create, save, show, edit, update, delete} actions. This is only a starting point, or used for reference.
What I typically do for public facing apps is setup URL mappings that handle routing based on HTTP methods. See http://grails.org/doc/latest/guide/theWebLayer.html#mappingHTTP for details.
Basically, this lets you do something like:
static mappings = {
"/product/$id"(controller:"product") {
action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]
}
}
In a controller, the actions should be separate as they serve different purposes. Grails lets you setup URL Mappings to handle HTTP method routing.
Upvotes: 8
Reputation: 75681
The code generated by the generate-controller
and generate-all
is just a convenience and a suggestion of what to do. It's generated into your application though, so edit it as needed, or write everything from scratch if you prefer.
The alternative to a create
action that accepts GET requests and just creates a new instance and renders the GSP to create an instance, plus a save
action that only accepts POST requests and does the actual creation if the instance is a single create
method that does both:
def create() {
if (request.post) {
// persist the new instance
}
else {
// render the GSP
}
}
This requires explicit logic to determine what to do, which clutters the code. The approach that Grails takes is cleaner since each action is more focused and only does one thing. This has an added benefit of making testing easier.
If you find that there ends up being shared logic between the two actions, you can always refactor that into private methods that both call.
Upvotes: 3