无法找到id = 1的CycleRoad(rails)

时间:2014-05-06 07:11:29

标签: ruby-on-rails

我收到此错误:

ActiveRecord::RecordNotFound in CycleRoadsController#destroy 

Couldn't find CycleRoad with id=1

你能帮助我吗?

这是我的代码:

class CycleRoadsController < ApplicationController

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

  def index
    @cycle_roads = CycleRoad.all
  end

  def new
        @cycle_road = CycleRoad.new
      end

def destroy
    @cycle_road.destroy
    respond_to do |format|
      format.html { redirect_to cycle_roads_url }
      format.json { head :no_content }
    end
  end

  private
    def set_cycle_road
      @cycle_road = CycleRoad.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def cycle_road_params
      params.require(:cycle_road).permit(:name, :begin, :finish, :km, :descriptionm)
    end
end

2 个答案:

答案 0 :(得分:2)

当ActiveRecord尝试查找您已通过并且找不到它的ID的记录时,会发生此错误。

因为;

可能会发生错误
  1. 如果您有意通过rails console删除了记录。

  2. 你的params [:id]被任何方法覆盖(可能是你的set_cycle_road方法)。

    使用rails logging检查&#34; delete&#34;中的params [:id]。方法并尝试纠正代码。

答案 1 :(得分:1)

before_filter方法set_cycle_road用于destroy操作找到cycle_road,如果在params中传递的某个id的循环道路不存在find会抛出错误。您可以使用where来处理此问题。

def set_cycle_road
  @cycle_road = CycleRoad.where("id = ?", params[:id]).first
  if @cycle_road.blank?
    flash[:notice] = "Cycle road not found"
    redirect_to #your_path
  end
end