Skip to content

Instantly share code, notes, and snippets.

@claudiug
Created August 12, 2014 16:30
Show Gist options
  • Save claudiug/d92a235965d552ec3cac to your computer and use it in GitHub Desktop.
Save claudiug/d92a235965d552ec3cac to your computer and use it in GitHub Desktop.
class PostsController < ApplicationController
before_action :load_post, only: [:edit, :show, :update, :destroy]
def index
load_posts
end
def new
build_post
end
def create
build_post
save_post or render 'new'
end
def edit
load_post
build_post
end
def show
load_post
end
def update
load_post
build_post
save_post or render 'edit'
end
def destroy
load_post
@post.destroy
redirect_to posts_path
end
private
def post_params
end
def load_posts
@posts ||= post_scope.to_a
end
def build_post
@post ||= post_scope.build
@post.attributes = post_params
end
def save_post
if @post.save
redirect_to @post
else
render 'new'
end
end
def load_post
if params[:id].present?
post_scope.find(params[:id]) rescue ActiveRecord::RecordNotFound
else
Post.none
end
end
def post_scope
Post.all
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment