Last active
February 9, 2016 22:20
-
-
Save paulbaker3/58376e368a4bb4eee249 to your computer and use it in GitHub Desktop.
A typical Rails controller, found in Fearless Refactoring Rails Controllers pg 29 - 30
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ProductsController < ApplicationController | |
before_action :set_product, only: [:show, :edit, :update, :destroy] | |
before_filter :filter_the_things, only: [:create] | |
def index | |
@products = Product.all | |
end | |
def show | |
end | |
def new | |
@product = Product.new | |
end | |
def edit | |
end | |
def create | |
@product = Product.new(product_params) | |
respond_to do |format| | |
if @product.save | |
format.html { redirect_to @product, notice: 'Product was successfully created.' } | |
format.json { render :show, status: :created, location: @product } | |
else | |
format.html { render :new } | |
format.json { render json: @product.errors, status: :unprocessable_entity } | |
end | |
end | |
end | |
def update | |
respond_to do |format| | |
if @product.update(product_params) | |
format.html { redirect_to @product, notice: 'Product was successfully updated.' } | |
format.json { render :show, status: :ok, location: @product } | |
else | |
format.html { render :edit } | |
format.json { render json: @product.errors, status: :unprocessable_entity } | |
end | |
end | |
end | |
def destroy | |
@product.destroy | |
respond_to do |format| | |
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' } | |
format.json { head :no_content } | |
end | |
end | |
private | |
def set_product | |
@product = Product.find(params[:id]) | |
end | |
def product_params | |
params.require(:product).permit(:name, :description) | |
end | |
def filter_the_things | |
# contrived example code here | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment