Skip to content

Instantly share code, notes, and snippets.

@mm53bar
Last active August 29, 2015 14:10
Show Gist options
  • Save mm53bar/6e9603754c729c105c8d to your computer and use it in GitHub Desktop.
Save mm53bar/6e9603754c729c105c8d to your computer and use it in GitHub Desktop.
Roll your own managed exposure
# Updated to use `locals` and a getter
class ItemsController < ApplicationController
# don't need before_action anymore
#
# before_action :set_item, only: [:show, :edit, :update, :destroy]
def index
render locals: { items: items }
end
def show
render locals: { item: item }
end
def new
render locals: { item: Item.new }
end
def edit
render locals: { item: item }
end
def create
self.item = Item.new(item_params)
if item.save
redirect_to item, notice: 'Item was successfully created.'
else
render :new, locals: { item: item }
end
end
def update
if item.update(item_params)
redirect_to item, notice: 'Item was successfully updated.'
else
render :edit, locals: { item: item }
end
end
def destroy
item.destroy
redirect_to items_url, notice: 'Item was successfully destroyed.'
end
end
private
def items
@item ||= Item.all
end
def item
@item ||= Item.find(params[:id])
end
def item=(item)
@item = item
end
def item_params
params[:item]
end
end
# Scaffolded controller
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
def index
@items = Item.all
end
def show
end
def new
@item = Item.new
end
def edit
end
def create
@item = Item.new(item_params)
if @item.save
redirect_to @item, notice: 'Item was successfully created.'
else
render :new
end
end
def update
if @item.update(item_params)
redirect_to @item, notice: 'Item was successfully updated.'
else
render :edit
end
end
def destroy
@item.destroy
redirect_to items_url, notice: 'Item was successfully destroyed.'
end
end
private
def set_item
@item = Item.find(params[:id])
end
def item_params
params[:item]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment