Skip to content

Instantly share code, notes, and snippets.

@eliotsykes
Last active March 14, 2017 10:15
Show Gist options
  • Save eliotsykes/2f586cada450b2731c51b0ff01a3f125 to your computer and use it in GitHub Desktop.
Save eliotsykes/2f586cada450b2731c51b0ff01a3f125 to your computer and use it in GitHub Desktop.
ThingsController - Typical Controller Structure
# For database-backed models:
class Thing < ApplicationRecord
validates :name, presence: true
end
# For Plain Old Ruby Object models:
class Thing
include ActiveModel::Model
attr_accessor :name, :description
validates :name, presence: true
# DIY `save`, `destroy`, `update` methods only if needed, and use
# more appropriate verbs as method names if they reveal the intention
# more clearly.
def save
...
end
def destroy
...
end
def update
...
end
end
# Pretty much the output from `rails generate scaffold Thing` with a few tweaks:
# - Replace `before_action :set_thing, only: ...` with `find_thing` (avoid Mystery Guest)
# - Specializes in serving HTML (JSON handling commented out and `respond_to` use removed.)
class ThingsController < ApplicationController
def index
@things = Thing.all
end
def show
@thing = find_thing
end
def new
@thing = Thing.new
end
def edit
@thing = find_thing
end
def create
@thing = Thing.new(thing_params)
if @thing.save
redirect_to @thing, notice: 'Thing was successfully created.'
# render :show, status: :created, location: @thing
else
render :new
# render json: @thing.errors, status: :unprocessable_entity
end
end
def update
@thing = find_thing
if @thing.update(thing_params)
redirect_to @thing, notice: 'Thing was successfully updated.'
# render :show, status: :ok, location: @thing
else
render :edit
# render json: @thing.errors, status: :unprocessable_entity
end
end
def destroy
@thing = find_thing
@thing.destroy
redirect_to things_url, notice: 'Thing was successfully destroyed.'
# head :no_content
end
private
def find_thing
Thing.find(params[:id])
end
def thing_params
params.require(:thing).permit(:name, :description)
end
end
@eliotsykes
Copy link
Author

eliotsykes commented Mar 14, 2017

removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment