前提・実現したいこと
レビュー機能を実装しており、編集画面へ遷移する際にエラーが発生するため、その解決を行いたいです。
index.html.erb→edit.html.erbへの遷移
※createアクションは問題なく実施できます
発生している問題・エラーメッセージ
ActiveRecord::RecordNotFound in ReviewsController#edit Couldn't find Post with 'id'=1
rails routes
search_posts GET /posts/search(.:format) posts#search posts GET /posts(.:format) posts#index POST /posts(.:format) posts#create new_post GET /posts/new(.:format) posts#new edit_post GET /posts/:id/edit(.:format) posts#edit post PATCH /posts/:id(.:format) posts#update PUT /posts/:id(.:format) posts#update DELETE /posts/:id(.:format) posts#destroy post_reviews GET /posts/:post_id/reviews(.:format) reviews#index POST /posts/:post_id/reviews(.:format) reviews#create new_post_review GET /posts/:post_id/reviews/new(.:format) reviews#new edit_review GET /reviews/:id/edit(.:format) reviews#edit review PATCH /reviews/:id(.:format) reviews#update PUT /reviews/:id(.:format) reviews#update DELETE /reviews/:id(.:format) reviews#destroy
route.rb
resources :posts, only: [:index, :new, :create, :edit, :update, :destroy], shallow: true do resources :reviews, only: [:index, :new, :create, :edit, :update, :destroy] end
reviews_controller.rb
class ReviewsController < ApplicationController before_action :set_post_id, only: [:index, :new, :create] before_action :set_post, only: [:edit, :update, :destroy] def index @review = Review.where(post_id: @post.id) end def edit @review = Review.find(params[:id]) end private def set_post_id @post = Post.find(params[:post_id]) end def set_post @post = Post.find(params[:id]) ←ココでエラー発生 end end
model
class Post < ApplicationRecord has_many :reviews, dependent: :destroy has_many :consignment_side_users, through: :reviews end class Review < ApplicationRecord belongs_to :consignment_side_user belongs_to :post end
index.html.erb
※該当箇所のみ抜粋 <% @review.each do |review| %> 省略 <%= link_to edit_review_path(review.id), method: :get, class:"posted-edit-btn" do %> <i class="fas fa-edit">編集する</i> <% end %> 省略 <% end %>
edit.html.erb
※該当箇所のみ抜粋 <%= render "shared/review_form" %>
shared/_review_form.html.erb
※該当箇所のみ抜粋 <div class="review-company-info"> <ul class="review-company-info-items"> <li class="review-company-info-item"> <%= image_tag @post.image, class: "review-company-img" %> </li> <li class="review-company-info-item"> <%= @post.company_name %> </li> </ul> </div> <%= form_with(model: [@post, @review], local: true) do |f| %> <%= f.submit "投稿する" ,class:"register-bronze-btn" %> <% end %>
試したこと
・@postの取得方法をfind_by(id: params[:id])に変更→nil
・@post = Post.find(params[:post_id])で実施→Couldn't find Post without an ID
補足情報(FW/ツールのバージョンなど)
ruby 2.7.2
Rails 6.1.3.1
vscode
MySQL
回答1件
あなたの回答
tips
プレビュー