我收到此错误:
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
有人知道,有什么不对吗?
答案 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]