Skip to content

Instantly share code, notes, and snippets.

@danielbeardsley
Created November 19, 2009 05:57
Show Gist options
  • Save danielbeardsley/238577 to your computer and use it in GitHub Desktop.
Save danielbeardsley/238577 to your computer and use it in GitHub Desktop.
A Generalized Json Controller for use with extjs-mvc and Restful CRUD
class JsonController < ApplicationController
rescue_from ActiveRecord::RecordNotFound do |exception|
render :json => { :success => false }, :status => :not_found
end
before_filter :find_record, :only => [ :get, :update, :destroy ]
layout 'base'
class << self
attr_accessor :model_class
end
def self.active_record_model_class (in_model)
#if a model is passed in use that, if anything else lookup it up
self.model_class = in_model.is_a?(ActiveRecord::Base) ? in_model : in_model.to_s.camelcase.constantize
end
def index
respond_to do |format|
format.html
format.json {
@record_hashes ||= scoped_model.all.map(&:to_record)
render :json => {:success => true, :total => @record_hashes.length, :data => @record_hashes }
}
end
end
def create
reject_non_attributes
@record = scoped_model.new(params[:data])
success = @record.save
error_messages = success ? nil : @record.errors.full_messages.join(', ')
render :json => {
:success => success,
:message => error_messages || "Created the record",
:data => @record.to_record}
end
def update
reject_non_attributes
success = @record.update_attributes(params["data"])
error_messages = success ? nil : @record.errors.full_messages.join(', ')
render :json => {
:success => success,
:message => error_messages || "Updated the record",
:data => @record.to_record}
end
def destroy
success = @record.destroy
render :json => {
:success => success,
:message => "Deleted the record"}
end
protected
def find_record
@record = scoped_model.find(params[:id]) if params[:id]
end
def reject_non_attributes()
#remove incoming attributes that aren't really columns
names = model.column_names
params["data"].reject!{|key, value| !names.include? key} if params["data"]
end
def scoped_model
model
end
def model
self.class.model_class ||= model_from_controller_name
end
def model_from_controller_name
#try to infer the model name from the controller if it hasn't been set
controller = controller_class_name.sub(/Controller$/, '')
controller.singularize.constantize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment