DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Use One Function For Get And Put Actions

01.19.2006
| 1020 views |
  • submit to reddit
        This template enables you to use only one function to display a template and process it with the same one.

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
    

Comments

Snippets Manager replied on Fri, 2006/02/17 - 8:17pm

The shorter version is much better. In the original, the post will be saved for a "HEAD" request. Better to assume readability, and check for writability.

Snippets Manager replied on Thu, 2006/01/19 - 9:09pm

You can simplify this down to... def new @post = Post.new(params[:post]) if request.post? and @post.save flash[:notice] = 'Post was successfully created' redirect_to :action => 'index' end end ...don't think there is any downside to this shorter version.