我一直在研究Ruby on Rails应用程序,但是当我访问 http://localhost:3000/posts/2/reviews/new 时,我收到此错误'无法找到帖子'id'= 2'。我已经在帖子资源中嵌套了评论,并将post_id分配给2,但是当我想写一篇新的评论时,我得到了上面的错误。我在这里找不到什么问题。
reviews_controller.rb
class ReviewsController < ApplicationController
before_action :set_review, only: [ :edit, :update, :destroy]
before_action :set_post
before_action :authenticate_user!
respond_to :html
def new
@review = Review.new
respond_with(@review)
end
def edit
end
def create
@review = Review.new(review_params)
@review.user_id = current_user.id
@review.post_id = @post.id
@review.save
redirect_to root_path
end
def update
@review.update(review_params)
respond_with(@review)
end
def destroy
@review.destroy
respond_with(@review)
end
private
def set_review
@review = Review.find(params[:id])
end
def set_post
@post = Post.find(params[:post_id])
end
def review_params
params.require(:review).permit(:comment)
end
end
的routes.rb
Rails.application.routes.draw do
devise_for :users
resources :posts do
resources :reviews , except: [:show,:index]
end
get 'pages/help'
get 'pages/blog'
get 'pages/contact'
resources :posts
root 'posts#index'
end
posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
@posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
end
# GET /posts/new
def new
@post = Post.new
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { render :show, status: :ok, location: @post }
else
format.html { render :edit }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:title, :description)
end
end
答案 0 :(得分:0)
这只是意味着你的数据库不包含id为2的Post,我想你是创建它然后用你的脚手架控制器销毁它。
您可以采取哪些措施来解决问题,在set_post
下添加到get_post
(将其更改为ReviewsController
以应用更好的命名)方法:
def set_post
unless @post = Post.where(id: params[:post_id]).first
redirect_to posts_path, flash: {alert: "Post doesn't exists"}
end
end
您还可以执行任何操作,而不是像显示404页面那样显示警告。