[Rails] 메모 삭제 기능의 구현에 빠져 있으므로 먼저 해결하십시오.

12225 단어 Rails

개시하다


라일스에 대한 이해를 깊게 하기 위해 트위터 기능을 자체 장착하는 과정에서 어떤 Tweet에 대한 댓글 삭제 기능까지 더해지면서 오류가 계속 나오는 수렁에 빠졌다.
잘못된 내용은 ActiveRecord::RecordNotFound (Couldn't find Comment without an ID)입니다.

팔람스가 아이디를 얻지 못했다는 얘기지.
대충 해결했으니까 메모지에 쓰세요.
※ 결론은 뿌리 설정이 잘못되었습니다.

관계



Commeent는 User 및 Tweet의 중간 테이블로 작성됩니다.
이번 댓글 삭제는 어느 Tweet의 것입니까Comment?이런 곳이 필요하다.

오류 시 설치 내용


먼저 오류가 발생했을 때의 실복을 쓴다.

루트 설정


routes.rb

# ---中略--- #

  resources :tweets do
    resources :comments, only: [:create, :destroy]
  end
어떤 트위터에 대한 댓글을 간단하게 설정하기 위해서다.
/tweets/:tweet_id/comments/:id(.:format)

결론은 이것이 문제가 있는 것 같다는 것이다.

컨트롤러 설정


삭제 기능과 관련된 컨트롤러 설정은 다음과 같다.
Comment 테이블에서 받은 Comment id에 맞는 설명을 삭제합니다.
comments_controller.rb
class CommentsController < ApplicationController

# ---中略--- #

  def destroy
    Comment.find(params[:id]).destroy
    redirect_to tweets_path
  end
end
이번에 삭제된 주소는 Tweets입니다.Tweet 화면을 path로 건너뜁니다.

뷰 설정


가령@comments 기고문 리뷰가 제출된 경우
/tweets/show.html.erb

# ---中略--- #

<% @comments.each do |comment| %>
  <p><span>コメント内容: </span><%= comment.body %></p>
  <p><%=link_to "削除", tweet_comments_path(comment.id), method: :delete %></p>
<% end %>

라우팅 확인 후 Tweetcomments DELEAT는/tweets/:tweet_id/comments/:id(.:format)경로의 쓰기 방법은 tweet_comments_path입니다.
()라는 내용에 취득하고 싶은 것comment.id을 넣었다.

오류 결과



이러한 설치를 토대로 '삭제' 단추를 누르면 방금 ActiveRecord::RecordNotFound (Couldn't find Comment without an ID)의 오류가 발생합니다.

실험


틀린 문장tweet_comments_path(comment.id)이 틀림없다고 생각해서 tweet_comments_path(comment.tweet.id)해 보기로 했어요.
/tweets/show.html.erb

# ---中略--- #

<% @comments.each do |comment| %>
  <p><span>コメント内容: </span><%= comment.body %></p>
  <p><%=link_to "削除", tweet_comments_path(comment.tweet.id), method: :delete %></p>
<% end %>
컨트롤러에 Tweet이 있습니다.id를 수락합니다.
comments_controller.rb
class CommentsController < ApplicationController

# ---中略--- #

  def destroy
    comment = Comment.find_by(tweet_id: params[:tweet_id])
    comment.destroy
    redirect_to tweets_path
  end
end
Comment.id를 교부하지 않기 때문에 삽입부분resources이 아니라resource.
resources 상태를 유지하면 라우팅 오류가 발생합니다.
routes.rb

# ---中略--- #

  resources :tweets do
    resource :comments, only: [:create, :destroy]
  end
실제 가동 후 다음과 같은 것을 발견하였다.
아래의 "두 번째 평론"을 삭제합니다.

결과:

위의 "평론을 원합니다"라는 오래된 평어가 삭제되었다.
실험성 Tweet.아이디만 냈으니까 그렇게 된 거죠.
삭제할 주석이 지정되지 않았기 때문입니다.
하지만 Param의 Tweet에서는납품된 것 같습니다.
네스트된 라우팅은 comment.tweet.id 줄 수 있지만 comment.id 줄 수 없어 잘 모르겠어
※ 원래 납품분은 comment.tweet.id여야 하지 않나요?
나는 루트와 컨트롤러의 설정을 원점으로 돌렸지만 이런 상황에서 comment.id를 너에게 맡기고 싶었지만 Tweet.id를 너에게 맡겼기 때문에 당연히 잘못된 것이라고 생각한다.

해결책


나는 루트 설정에comment의destroy 부분을 끼워 넣는 것을 포기했다.
routes.rb

# ---中略--- #

  resources :tweets do
    resource :comments, only: [:create]
  end
  resources :comments, only: [:destroy]
comments#destroy의 라우트를 확인한 후 다음과 같습니다.

컨트롤러 및 뷰 설정
comments_controller.rb
class CommentsController < ApplicationController

# ---中略--- #

  def destroy
    Comment.find(params[:id]).destroy
    redirect_to tweets_path
  end
end
/tweets/show.html.erb

# ---中略--- #

<% @comments.each do |comment| %>
  <p><span>コメント内容: </span><%= comment.body %></p>
  <p><%=link_to "削除", comment_path(comment.id), method: :delete %></p>
<% end %>
이렇게 하면 평론을 안전하게 삭제할 수 있다.

총결산


루트를 끼워 넣으면 얻을 수 없는 값이 있다는 것은 상상하기 어렵지만 잘 되지 않는다.
무슨 건의가 있으면 저에게 알려주세요.

수정점


9/2
우리의 문제는 건의를 받아 이미 해결되었으니 기술해 보아라.
문제는 다음과 같은 두 가지가 있다.

  • 아니오tweet_comments_pathtweet_comment_path
  • 네스트된 라우팅의 경우 2개의 매개변수
  • 가 필요합니다.
    Delete라면 s가 필요 없을 것 같아요.
    /tweets/show.html.erb
    # ---中略--- #
    
    <% @comments.each do |comment| %>
      <p><span>コメント内容: </span><%= comment.body %></p>
      <p><%=link_to "削除", tweet_comment_path(comment.tweet.id, comment.id), method: :delete %></p>
    <% end %>>
    
    comments_controller.rb
    class CommentsController < ApplicationController
    
    # ---中略--- #
    
      def destroy
        Comment.find_by(id: params[:id],tweet_id: params[:tweet_id]).destroy
        redirect_to tweets_path
      end
    end
    
    routes.rb
    
    # ---中略--- #
    
      resources :tweets do
        resources :comments, only: [:create, :destroy]
      end
    
    이렇게 하면 순조롭다.

    좋은 웹페이지 즐겨찾기