未定义的方法`destroy'为nil:NilClass(rails)

时间:2014-05-05 22:50:30

标签: ruby-on-rails

我收到此错误:

CycleRoadsController#destroy中的NoMethodError

未定义的方法`destroy'为零:NilClass(rails)。

这是来自控制器的代码,它们包含一种方法' destroy':

        respond_to do |format|
      if @cycle_road.save
        format.html { redirect_to @cycle_road, notice: 'Cycle road was successfully created.' }
        format.json { render action: 'show', status: :created, location: @cycle_road }
      else
        format.html { render action: 'new' }
        format.json { render json: @cycle_road.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @cycle_road.update(cycle_road_params)
        format.html { redirect_to @cycle_road, notice: 'Cycle road was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @cycle_road.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /cycle_roads/1
  # DELETE /cycle_roads/1.json
  def destroy
    @cycle_road.destroy
    respond_to do |format|
      format.html { redirect_to cycle_roads }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_cycle_road
      @cycle_road = CycleRoad.find(params[:id])
    end

    def cycle_road_params
      params.require(:cycle_road).permit(:name, :begin, :finish, :km, :description)
    end
end

有人知道,有什么不对吗?

2 个答案:

答案 0 :(得分:1)

在调用@cycle_road之前设置实例变量destroy

目前其nil错误显示为undefined method 'destroy' for nil:NilClass

根据共享控制器代码,您需要在destroy

before_action回调中添加set_cycle_road操作
class CycleRoadController < ApplicationController
  before_action :set_cycle_road, only: [:show, :edit, :update, :destroy]
  ## ...                                                         ^
  ##                                                          Add this
end

此回调将在调用@cycle_road操作之前设置destroy实例变量。

答案 1 :(得分:0)

正如上一个人提到的那样,@ cycle_road似乎是零。确保您有一个之前的行动:

class CycleRoadController < ApplicationController
  ...
  before_action :set_cycle_road
  ...

确保它针对您的destroy方法运行。即。

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