Rails中的ActiveRecord :: RecordNotFound错误

时间:2017-11-07 16:47:09

标签: ruby-on-rails activerecord ruby-on-rails-5.1

PicsController中的ActiveRecord :: RecordNotFound#show

无法找到带有'id'= 1

的Pic

提取的来源(第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

2 个答案:

答案 0 :(得分:1)

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

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

= link_to "Back", root_path
如果没有pic,

尝试挽救错误。

答案 1 :(得分:0)

我对一个对象和.permit这个rescue nil感到困惑。为什么需要它?

  

据我所知.permit只允许ActionController::Parametersmore details

所以也许你必须改写find_pic

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