Wednesday, March 12, 2014

Adding Delete Comment Feature into Blog Post

In /app/comments/_comment.html.erb,

<%= div_for comment do %>
    <p>
        <strong>
            Posted <%= time_ago_in_words(comment.created_at) %> ago
        </strong>
        <br/>
        <%= comment.body %><br/>
        <%= link_to 'Delete Comment', comment, method: :delete %>
    </p>
<% end %>

In /app/controllers/comments_controller.rb,

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create!(params[:comment])
    redirect_to @post
  end

  def destroy
    @post = Post.find(params[:id])
    @comment = Comment.find(params[:id])
    if @comment.destroy
      redirect_to @post
    end
  end
end

In config/routes.rb,

QuickBlog::Application.routes.draw do
  resources :comments
  
  resources :posts do
    resources :comments, :only => [:create, :destroy]
  end
end

Return to Internship Note (LoanStreet)
Previous Episode: Create Simple Rails App
Next Episode: Update Blog with Author

0 comments:

Post a Comment