【问题标题】:New to rails. Index action doesnt like my initialization method.. Why?铁轨新手。索引操作不喜欢我的初始化方法。为什么?
【发布时间】: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


【解决方案1】:

发生这种情况是因为当您定义 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]) 只会在显示操作时被调用。 你也可以使用:except 来做相反的事情。

【讨论】:

    【解决方案2】:

    根据评论编辑答案

    我得到一个错误的页面:ActiveRecord::RecordNotFound in ZombiesController#index 找不到没有 ID Rails.root 的 Zombie: C:/Sites/TwitterForZombies 应用程序跟踪 |框架跟踪 |满的 跟踪 app/controllers/zombies_controller.rb:85:in `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
    

    【讨论】:

    • 这不是问题 - @zombies 已在 before_filter 中分配
    • 是的。这应该由 before 过滤器来处理
    【解决方案3】:

    它确实有效,因为您需要返回(到您的索引视图)您的僵尸列表。 get_zombie_params() 正确执行,但不会将 @zombies 发送到 index() 操作。

    你需要做的:

    def index 
       @zombies = Zombie.all
       #... the rest of the code
    end
    

    【讨论】:

      猜你喜欢
      • 2010-10-29
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      相关资源
      最近更新 更多