【问题标题】:Error ActiveRecord::RecordNotFound in RailsRails 中的错误 ActiveRecord::RecordNotFound
【发布时间】:2017-11-07 16:47:09
【问题描述】:

ActiveRecord::RecordNotFound in PicsController#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

【问题讨论】:

  • pics表中没有记录
  • 如果您打开控制台并尝试 Pic.find(1),是否存在具有该 id 的记录?
  • 不要在问题中张贴图片。相反,剪切并粘贴相关文本。其他有同样问题的人稍后可能会遇到这个问题,但是如果您的图像主机删除了图像,那么这个问题将不再有意义。
  • 没有仍然显示错误 -> ActiveRecord::RecordNotFound: 找不到 'id'=1 的图片

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


【解决方案1】:

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

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

= link_to "Back", root_path

如果没有图片,请尝试挽救错误。

【讨论】:

  • 工作!!谢谢。
【解决方案2】:

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

据我所知,.permit 只允许在 ActionController::Parametersmore details 上使用

所以也许你必须重写 find_pic:

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

【讨论】:

  • 如果不添加该许可,则会出现另一个错误。 ActiveRecord::RecordNotFound in PicsController#show
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
相关资源
最近更新 更多