lundi 20 novembre 2017

Why my delete post function doesn't work?

I was trying to make a simple blog application using Rails. I added function like "creating a new post", "edit a post" I wanted also to add a delete function... but it doesn't work. Please help me!

Here is my "posts_controller.rb" file

class PostsController < ApplicationController
def index
    @posts = Post.all.order('created_at DESC')
end

def new
    @post = Post.new 
end

def create
    @post = Post.new(post_params)
    @post.save

    if @post.save
        redirect_to @post 
    else 
        render 'new'
    end
end

def show 
    @post = Post.find(params[:id])
end

def edit 
    @post = Post.find(params[:id])
end 

def update
    @post = Post.find(params[:id])

    if @post.update(params[:post].permit(:title, :body))
        redirect_to @post
    else 
        render 'edit'
    end
end

def destroy
    @post = Post.find(params[:id])
    @post.destroy

    redirect_to post_path
end

private 
    def post_params 
        params.require(:post).permit(:title, :body)
    end
end

"show_html.erb" file:

<div id="post_content">
<h1 class="title">
    <%= @post.title %>
</h1>

<p class="date">
    Submitted <%= time_ago_in_words(@post.created_at) %> Ago
    | <%= link_to 'Edit', edit_post_path(@post) %>
    | <%= link_to 'Delete', post_path(@post),
          method: :delete,
          data: { confirm: 'Are you sure?' } %>
</p>

<p class="body">
    <%= @post.body %>
</p>
</div>

And it gave me this error: ActiveRecord::RecordNotFound in PostsController#show Couldn't find Post with 'id'=7 Extracted source (around line #22):

def show 
    @post = Post.find(params[:id])
end

def edit 

THANK YOU!

Aucun commentaire:

Enregistrer un commentaire