我对rails很新,并且使用代码来使页面正常工作。 链接 localhost:3000 / zombies / 1 有效(显示操作) 但是localhost:3000 / zombies(索引动作)没有。以下是我的路线和控制器:
路线: 资源:僵尸
CONTROLLER是:
class ZombiesController < ApplicationController
before_filter :get_zombie_params
def index
respond_to do |format|
format.html # index.html.erb
format.json { render json: @zombies }
end
end
def show
@disp_zombie = increase_age @zombie, 15
@zombie_new_age = @disp_zombie
respond_to do |format|
format.html # show.html.erb
format.json { render json: @zombie }
end
end
def increase_age zombie, incr
zombie = zombie.age + incr
end
def get_zombie_params
@zombie=Zombie.find(params[:id])
@zombies = Zombie.all
end
end
为什么会这样?
答案 0 :(得分:4)
根据评论编辑答案
我得到一个错误的页面:ActiveRecord :: RecordNotFound in ZombiesController #index找不到没有ID Rails.root的Zombie: C:/ Sites / TwitterForZombies应用程序跟踪|框架跟踪|充分 跟踪app / controllers / zombies_controller.rb:85:在`get_zombie_params'
调用localhost:3000/zombies
操作的网址index
不包含id
参数。
这就是应用程序在@zombie=Zombie.find(params[:id])
失败的原因。
如果您想解决此问题,请仅在before_filter
操作时使用show
。
before_filter :get_zombie_params, only: :show
并将其插入到我最初建议的索引操作中。
def index
@zombies = Zombies.all
...
end
答案 1 :(得分:2)
这种情况正在发生,因为当您定义resources :zombies
时,您将获得以下路线:
/zombies
/zombies/:id
因此,当导航到/zombies
时,您没有params[:id]
,那就是nil
Zombie.find
方法无法找到具有给定ID的记录并停止进一步处理您的代码,则会引发错误。
如果您不希望在没有结果的情况下引发异常,则可以使用Zombie.find_by_id
。
但我认为这不是你想要的,你宁愿定义get_zombie_by_id
方法和get_all_zombies
方法,并将代码与get_zombie_params
然后你必须通过更改你的before_filter来定义应该调用哪个方法,在你的情况下:
before_filter :get_zombie_by_id, :only => :show
before_filter :get_all_zombies, :only => :index
这种方式Zombie.find(params[:id])
只会在show动作时被调用。
您也可以使用:except
执行相反的操作。
答案 2 :(得分:0)
它确实有效,因为您需要将您的僵尸列表发送回(到您的索引视图)。 get_zombie_params()可以执行,但不会将@zombies发送到index()操作。
你需要这样做:
def index
@zombies = Zombie.all
#... the rest of the code
end