Ruby on Rails' respond_to causing strange error

瘦欲@ 提交于 2020-05-02 02:58:26

问题


There is another respond_to for the usual case, and a special case when a param[:top] is passed in, so there is another respond_to earlier in the code:

      respond_to do |format|
        format.html { render :top_page_analytics }
        format.json { render :json => @analytics }
        format.xml { render :xml => @analytics }
        return
      end

but the above code actually gave a strange error for missing template for json, and further debug leading to:

      respond_to do |format|
        format.html { render :top_page_analytics }
        format.json { render :json => @analytics }
        format.xml { render :xml => @analytics }
      end
      return

which fixes the bug. The return is needed so that there will be no "double render error" because the program will flow to the other respond_to. But I wonder the strange syntax of respond_to, looking somewhat like a case statement, may cause error like that at the top?


回答1:


The return can't go there because you're passing a block. The block isn't executed in the immediate context of the controller action. When you return from the block, you're actually returning from the function yielding (respond_to), not the controller action.



来源:https://stackoverflow.com/questions/3730697/ruby-on-rails-respond-to-causing-strange-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!