2017-11-20 2 views
0

레일스를 사용하여 간단한 블로그 응용 프로그램을 만들려고했습니다. "새 게시물 만들기", "게시물 편집"과 같은 기능을 추가했습니다. 삭제 기능을 추가하고 싶었습니다. 그러나 그것은 효과가 없습니다. 제발 도와주세요!내 게시물 삭제 기능이 작동하지 않는 이유는 무엇입니까?

여기 내 "posts_controller.rb"파일

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"파일입니다

<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> 

그리고 그것은 나에게이 오류 준 : 액티브 :: RecordNotFound가 PostsController 번호 쇼를 'id'= 7 인 게시물을 찾을 수 없습니다. 추출 된 소스 (라인 22 번 주변) :

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

자바 스크립트 오류로 인해 요청이 GET으로 전송되었습니다. Rails는'jquery-ujs'에 의존하여 링크로부터 GET 방식이 아닌 요청을 보냅니다. 브라우저 콘솔에서 오류를 확인하십시오. 또한 <% = button_to 'Delete', @ post, method : : delete, data : {confirm : 'Are you sure?'를 사용할 수 있습니다. } %>'JS에 의존하지 않습니다. – max

+0

이 질문은 매일 발생하지만 좋은 중복 표적을 찾을 수 없습니다. 어떤 아이디어? – max

+0

확인. 고마워요. 나는 버튼 솔루션을 시도하고 작동하지 않으면 당신을 쓸 것입니다. –

답변

1

destroy 방법에서 방금 삭제 한 postshow 경로로 리디렉션 중입니다. 그래서 RecordNotFound 오류가 발생합니다.

destroy 방법에서 redirect_to post_path에서 redirect_to posts_path으로 변경하고이 오류가 없어지는지 확인하십시오.

+0

효과가있었습니다! 고마워요! –

관련 문제