我是Rails的新手,并使用代码来使页面正常工作。链接 localhost:3000/Zombies/1 Works(显示动作)但是Localhost:3000/僵尸(索引动作)没有。以下是我的路线和控制器:
路由是: 资源:僵尸
控制器是:
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
为什么这是?
根据评论编辑答案
我获得了一个错误:activerecord :: recordnotfound的页面 没有ID Rails.ROOT: c:/sites/twitterforzombies应用程序跟踪|框架跟踪|满的 跟踪应用程序/控制器/Zombies_controller.rb:85:在`get_zombie_params'
index
操作的URL,localhost:3000/zombies
不包括id
参数。
这就是该应用在@zombie=Zombie.find(params[:id])
失败的原因。
如果要解决此问题,请仅在show
操作上使用before_filter
。
before_filter :get_zombie_params, only: :show
并将其插入我最初建议的索引动作中。
def index
@zombies = Zombies.all
...
end
这正在发生,因为定义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 :get_zombie_by_id, :only => :show
before_filter :get_all_zombies, :only => :index
这样,只有在演出动作中,Zombie.find(params[:id])
才会被调用。您也可以使用:except
进行相反的操作。
它确实有效,因为您需要将僵尸列表发送回(到索引视图)。get_zombie_params()符合正确的责任,但不会将 @zombies发送到index()操作。
您需要做:
def index
@zombies = Zombie.all
#... the rest of the code
end