Skip to content

Instantly share code, notes, and snippets.

@jonahoffline
Created December 26, 2012 06:25
Show Gist options
  • Save jonahoffline/4378365 to your computer and use it in GitHub Desktop.
Save jonahoffline/4378365 to your computer and use it in GitHub Desktop.
Rails 4 example of strong_parameters. This is the new way of doing controllers and whitelisting parameters.
class HeadlinesController < ApplicationController
before_action :set_headline, only: [:show, :edit, :update, :destroy]
# GET /headlines
# GET /headlines.json
def index
@headlines = Headline.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @headlines }
end
end
# GET /headlines/1
# GET /headlines/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @headline }
end
end
# GET /headlines/new
# GET /headlines/new.json
def new
@headline = Headline.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @headline }
end
end
# GET /headlines/1/edit
def edit
end
# POST /headlines
# POST /headlines.json
def create
@headline = Headline.new(headline_params)
respond_to do |format|
if @headline.save
format.html { redirect_to @headline, notice: 'Headline was successfully created.' }
format.json { render json: @headline, status: :created, location: @headline }
else
format.html { render action: "new" }
format.json { render json: @headline.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /headlines/1
# PATCH/PUT /headlines/1.json
def update
respond_to do |format|
if @headline.update_attributes(headline_params)
format.html { redirect_to @headline, notice: 'Headline was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @headline.errors, status: :unprocessable_entity }
end
end
end
# DELETE /headlines/1
# DELETE /headlines/1.json
def destroy
@headline.destroy
respond_to do |format|
format.html { redirect_to headlines_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_headline
@headline = Headline.find(params[:id])
end
# Use this method to whitelist the permissible parameters. Example:
# params.require(:person).permit(:name, :age)
#
# Also, you can specialize this method with per-user checking of permissible
# attributes.
def headline_params
params.require(:headline).permit(:title, :body, :published_date, :available)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment