Skip to content

Instantly share code, notes, and snippets.

@regularlady
Created February 8, 2016 23:19
Show Gist options
  • Save regularlady/5c69bc756e1d3c2a7352 to your computer and use it in GitHub Desktop.
Save regularlady/5c69bc756e1d3c2a7352 to your computer and use it in GitHub Desktop.
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
end
def new
# Hannah remove please, add in next line: @topic = Topic.find(params[:id])
@topic = Topic.find(params[:topic_id])
@post = Post.new
end
def create
#create a new instance of post
@post = Post.new
@post.title = params[:post][:title]
@post.body = params[:post][:body]
# Hannah remove please. Add in next 2 lines: @topic = Topic.find(params[:id])
# @post.topic = topic
topic = Topic.find(params[:topic_id])
@post.topic = topic
#if post is successfully saved, display success message
if @post.save
flash[:notice] = "Post was saved."
# remove @topic and make it topic
redirect_to [topic, @post]
else
#if save is unsuccessful, display error message and render the new view again
flash.now[:alert] = "There was an error saving the post. Please try again."
render :new
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
@post.title = params[:post][:title]
@post.body = params[:post][:body]
if @post.save
flash[:notice] = "Post was updated"
# Hannah remove please and add in next line: redirect_to [@topic, @post]
redirect_to [@post.topic, @post]
else
flash.now[:alert] = "There was an error updating. Please try again."
render :edit
end
end
def destroy
@post = Post.find(params[:id])
if @post.destroy
flash[:notice] = "\"#{@post.title}\" was deleted successfully."
redirect_to @post.topic
else
flash.now[:alert] = "There was a problem deleting the post."
render :show
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment