Rails 中的错误 ActiveRecord::RecordNotFound

Error ActiveRecord::RecordNotFound in Rails

PicsController 中的 ActiveRecord::RecordNotFound#show

找不到 'id'=1

的图片

提取的源代码(大约第 34 行):

  def find_pic
    @pic = Pic.find(params[:id])
  end

我无法解决错误。

我的pics_controller.rb如下

class PicsController < ApplicationController

      before_action :find_pic, only: [:show, :edit, :update, :destroy]

      def index   
      end
      def show
      end   
      def new
        @pic = Pic.new
      end 
      def create
        @pic = current_user.pics.build(pic_params)
        if @pic.save
          redirect_to @pic,notice: "Yesss! It was posted!"
        else
          render 'new'
        end
      end
      private   
       def pic_params
        params.require(:pic).permit(:title, :description)
      end
      def find_pic
        @pic = Pic.find(params[:id]).permit(:title) rescue nil
      end
    end

我的show.html.haml

%h1= @pic.title
%p= @pic.description

= link_to "Back", root_path

更新:我运行 rake routes 这是输出。

$ rake routes
  Prefix Verb   URI Pattern              Controller#Action
    pics GET    /pics(.:format)          pics#index
         POST   /pics(.:format)          pics#create
 new_pic GET    /pics/new(.:format)      pics#new
edit_pic GET    /pics/:id/edit(.:format) pics#edit
     pic GET    /pics/:id(.:format)      pics#show
         PATCH  /pics/:id(.:format)      pics#update
         PUT    /pics/:id(.:format)      pics#update
         DELETE /pics/:id(.:format)      pics#destroy
    root GET    /                        pics#index

你应该尝试 @pic = Pic.find(params[:id]) 应该足够了。

%h1= @pic.title if @pic.present?
%p= @pic.description if @pic.present?

= link_to "Back", root_path

如果没有图片,请尝试修复错误。

我对对象上的 .permitrescue nil 事物感到困惑。为什么需要它?

As far as I know .permit is allowed only on ActionController::Parameters, more details

所以也许你必须重写 find_pic:

def find_pic
  @pic = Pic.find(params[:id])
end