【问题标题】:In the update action a NoMethodError is thrown在更新操作中抛出 NoMethodError
【发布时间】:2023-03-18 06:10:01
【问题描述】:

这是我的源代码

 def update
    @recipe = Recipe.find(params[:id])

    respond_to do |format|
      if @recipe.update_attributes(params[:recipe])
        format.html {redirect_to :action => "edit" }
      end
    end
  end

我在这一行得到一个错误

respond_to do |format|

并且错误消息是“您没有预料到它有一个 nil 对象。在评估 nil.call 时发生错误”。

堆栈跟踪中的五行如下

/Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/mime_responds.rb:175:in `respond'
/Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/mime_responds.rb:173:in `each'
/Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/mime_responds.rb:173:in `respond'
/Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/mime_responds.rb:107:in `respond_to'
/Path from my machine to the app/app/controllers/recipes_controller.rb:43:in `update'

我不知道如何调试它,也无法理解如何引发此错误。

非常感谢任何帮助。

谢谢

【问题讨论】:

    标签: ruby-on-rails actionpack


    【解决方案1】:

    如果您不响应非 html 客户端,则不必使用 respond_to。

    尝试将方法更改为:

      if @recipe.update_attributes(params[:recipe])
       redirect_to :action => "edit"
      end
    

    如果可行,则错误看起来像是在您应用的 mime 类型配置中的某个位置。

    【讨论】:

    • 谢谢托比。它有帮助,现在我必须检查我的 mime 类型配置。
    【解决方案2】:

    当您不使用 yieled format 对象时,会出现此神秘错误。事实上,当 update_attributes 调用失败时,你确实应该做点什么,例如渲染 edit 模板:

      def update
        @recipe = Recipe.find(params[:id])
    
        respond_to do |format|
          if @recipe.update_attributes(params[:recipe])
            format.html { redirect_to [:edit, @recipe] }
          else 
            format.html { render :template => 'edit' }
          end
        end
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2014-10-18
      • 1970-01-01
      • 2013-12-27
      • 2016-04-13
      相关资源
      最近更新 更多