Friday, November 2, 2007

Merb Crud Controller

The other day I decided to try a complete CRUD controller using the new provides format and Active Record. It supports XML, Javascript, YAML formats where appropriate and HTML across all actions. The built in error handling in Merb also helps to clean things up.

Well. Here it is, for better or worse. I really like it though ;)

class Posts < Application
provides :xml, :js, :yaml

def index
@posts = Post.find(:all)
render @posts
end

def show
@post = Post.find(params[:id])
render @post
end

def new
only_provides :html
@post = Post.new(params[:post])
render
end

def create
@post = Post.new(params[:post])
if @post.save
redirect url(:post, @post)
else
render :action => :new
end
end

def edit
only_provides :html
@post = Post.find(params[:id])
render
end

def update
@post = Post.find(params[:id])
if @post.update_attributes(params[:post])
redirect url(:post, @post)
else
raise BadRequest
end
end

def destroy
@post = Post.find(params[:id])
if @post.destroy
redirect url(:posts)
else
raise BadRequest
end
end
end