I’ve been using this template on most of my CRUD controllers.
class CommentsController < ApplicationController
meantime_filter :set_scope
before_filter :find_comment, :only => %w(show edit update destroy)
def index
@comments = Comment.find(:all)
end
def new
@Comment = Comment.new
end
def create
@comment = Comment.create!(params[:comment])
redirect_to comment_url(@comment)
rescue ActiveRecord::RecordInvalid => invaild
@comment = invaild.record
render :action => ‘new’
end
def show
end
def edit
end
def update
@comment.attributes = params[:comment]
@comment.save!
redirect_to comment_url
rescue ActiveRecord::RecordInvalid
render :action => ‘edit’
end
def destroy
@comment.destroy
redirect_to comments_url
end
protected
def find_comment
set_scope { @comment = Comment.find(params[:id]) }
end
def set_scope
scope = { :post_id => params[:post_id] }
Comment.with_scope( :find => { :conditions => scope }, :create =>
scope ) { yield }
end
end