class API::V1::<%= resource.pluralize %>Controller < APIController <% if allowed_fields_provided? %>allow_query_on <%= allowed_fields %><% end %> before_filter :build_resource, :only => :create <% if parent? %><% all_parents = parents %><% prev = all_parents.shift %> load_and_authorize_resource :<%= prev.singularize %>, :except => [:destroy] <% all_parents.each do |p| %>load_and_authorize_resource :<%= p.singularize %>, :through => :<%= prev.singularize %>, :except => [:destory]<% prev = p %> <% end %>load_and_authorize_resource :through => :<%= prev.singularize %>, :except => [:destory]<% if model_specified? %>, :class => "<%= model %>"<% end %> <% else %> load_and_authorize_resource :except => [:destory]<% if model_specified? %>, :class => "<%= model %>"<% end %> <% end %> # GET /api/v1/<%= resource.pluralize.underscore %> def index respond_with(@<%= resource.pluralize.underscore %>) end def create <% fields.each do |name, type| %><% if type == "has_many" %> <%= name.underscore %> = <%= name.singularize.camelize %>.where({:id => params[:<%= resource.underscore %>][:<%= name %>]}) @<%= resource.underscore %>.<%= name.underscore %> = <%= name.underscore %><% end %><% end %> if @<%= resource.underscore %>.save respond_with(@<%= resource.underscore %>) else respond_to do |format| format.json { render :json => {:fields => @<%= resource.underscore %>.errors}, :status => :unprocessable_entity } end end end def show respond_with(@<%= resource.underscore %>) end def update <% fields.each do |name, type| %><% if type == "has_many" %> <%= name.underscore %> = <%= name.singularize.camelize %>.where({:id => params[:<%= resource.underscore %>][:<%= name %>]}) @<%= resource.underscore %>.<%= name.underscore %> = <%= name.underscore %><% end %><% end %> if @<%= resource.underscore %>.update(resource_params) respond_with(@<%= resource.underscore %>) else respond_to do |format| format.json { render :json => {:fields => @<%= resource.underscore %>.errors}, :status => :unprocessable_entity } end end end def destroy ids = params[:id].split(",") @<%= resource.pluralize.underscore %> = <% if model_specified? %><%= model %><% else %>::<%= resource %><% end %>.where(:id => ids) authorize! :destroy, @<%= resource.pluralize.underscore %> @<%= resource.pluralize.underscore %>.destroy_all end def build_resource @<%= resource.underscore %> = <% if model_specified? %><%= model %><% else %>::<%= resource %><% end %>.new(resource_params) <% if parent? %>@<%= resource.underscore %>.<%= parents.last.singularize %> = <%= parents.last.singularize.camelize %>.find(params[:<%= parents.last.singularize %>_id])<% end %> end def resource_params params.require(:<%= resource.underscore %>).permit(:id<%= fields_as_params(:relations => true) %>) end end