【发布时间】:2012-10-13 22:32:36
【问题描述】:
我对 Rails 完全陌生,我在玩代码以使页面正常工作。 链接 localhost:3000/zombies/1 有效(显示操作) 但 localhost:3000/zombies (索引操作)没有。以下是我的路线和控制器:
路线是: 资源:僵尸
控制器是:
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
这是为什么?
【问题讨论】:
-
你能粘贴你收到的错误吗?
-
您的代码对我来说看起来不错。当你浏览到 /zombies/ 时实际发生了什么?是否会抛出异常?你得到一个空白页吗?更多信息将帮助我们为您提供帮助!
-
我得到一个错误页面:ActiveRecord::RecordNotFound in ZombiesController#index 找不到没有 ID Rails.root 的 Zombie: C:/Sites/TwitterForZombies Application追踪 |框架跟踪 |完整跟踪 app/controllers/zombies_controller.rb:85:in `get_zombie_params'
-
问题是你在两条路由上都运行了 before_filter。在展会上,您可以致电
Zombie.find(params[:id])和Zombie.all。但是在索引操作中,您没有任何参数,因此您的Zombie.find(params[:id]给您ActiveRecord错误。 -
谢谢 Mehul,有没有办法解决这个问题?我想在单独的 before 方法中初始化实例变量僵尸和僵尸。
标签: ruby-on-rails ruby model-view-controller