Skip to content

Instantly share code, notes, and snippets.

@novohispano
Last active August 29, 2015 14:22
Show Gist options
  • Save novohispano/5c5e30e84f296c9f68ce to your computer and use it in GitHub Desktop.
Save novohispano/5c5e30e84f296c9f68ce to your computer and use it in GitHub Desktop.
API Example
class ItemsController < ApplicationController
def index
@items = Item.all
respond_to do |format|
format.html { @items }
format.json { render json: @items }
format.xml { render xml: @items }
end
end
def show
@item = Item.find_by(id: params[:id])
respond_to do |format|
format.html { @item }
format.json { render json: @item }
format.xml { render xml: @item }
end
end
end
class ItemsController < ApplicationController
respond_to :html, :json, :xml
def index
@items = Item.all
respond_with @items
end
def show
@item = Item.find_by(id: params[:id])
respond_with @item
end
end
class ItemsController < ApplicationController
# More Code
def create
@item = Item.new(item_params)
if @item.save
respond_to do |format|
format.html { redirect_to items_path, notice: "The item was created." }
format.json { render json: @item }
format.xml { render xml: @item }
end
else
respond_to do |format|
format.html do
flash.now[:notice] = "The item was not created."
render :new
end
format.json { render json: { messages: @item.errors.messages}, status: 400 }
format.xml { render xml: { messages: @item.errors.messages}, status: 400 }
end
end
end
def update
@item = Item.find(params[:id])
if @item.update_attributes(item_params)
respond_to do |format|
format.html { redirect_to items_path, notice: "The item was updated." }
format.json { render json: @item }
format.xml { render xml: @item }
end
else
respond_to do |format|
format.html do
flash.now[:notice] = "The item was not updated."
render :edit
end
format.json { render json: { messages: @item.errors.messages}, status: 400 }
format.xml { render xml: { messages: @item.errors.messages}, status: 400 }
end
end
end
end
class Api::V1::ItemsController < ApplicationController
respond_to :json, :xml
def index
respond_with Item.all
end
def show
respond_with Item.find(params[:id])
end
def create
respond_with Item.create(item_params)
end
def update
respond_with Item.update(params[:id], item_params)
end
def delete
respond_with Item.destroy(params[:id])
end
private
def item_params
params.require(:item).permit(:name, :description, :image_url)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment