How To Combine Form Actions in Rails
May 20, 2006As I’ve done more development with Rails I’ve become more interested in refactoring and simplifying my code. One of the ways I’ve found to do that is to combine actions in object creation. This means going from having separate “new” and “create” actions to just having single “new” action.
How? The wonder of request.post?.
So let’s say I have an action “new” that lets a user fill out a form to create a new Widget. It might look something like this:
<%= start_form_tag :action => "create" %> <%= text_field "widget", "name" %> <%= submit_tag "create" %> <%= end_form_tag %>
With the corresponding actions in the controller:
def new @widget = Widget.new end def create @widget = Widget.new(params[:widget]) @widget.save end
So wouldn’t it be easier to just have one action for this whole process? I’d like to think so. Here’s the combined solution:
Change our form action:
<%= start_form_tag :action => "new" %>
And combine our controller actions:
def new
@widget = Widget.new
if request.post?
@widget = Widget.new(params[:widget])
@widget.save
end
end
Now our form redirects to itself, but it passes along the user entered form information as a post request. By checking for the presence of the post information in the request we can determine if the call of the “new” action is the first initial load or a user submit click.
The result is one less action in the controller and a simpler process for creating a new Widget. The process is the same for combining Edit/Update actions into a single Edit action.