This browser does not support basic Web standards, preventing the display of our site's intended design. May we suggest that you upgrade your browser?

Web Development Code Library RailsUse one action for get and post

Use one action for get and post

Simple example that shows how to use a single controller action to handle both get and post requests. This really comes in handy for those situations where you need to handle multiple objects.

def new
  if request.get?  # no post data, so create a new instance and render the template
    @post = Post.new
  else  # post-part, form was filled out and we can save the post
    @post = Post.new(params[:post])
    if @post.save
      flash[:notice] = 'Post was successfully created.'
      redirect_to :action => 'index'
    else
      render :action => 'new'
    end
  end
end
Excellence. Our Measure. Our Motto. Our Goal.