如何在Rails中处理没有响应

时间:2014-03-11 08:55:33

标签: ruby-on-rails

我在我的控制器中添加了一个函数,以提供一种通过Get请求添加记录的方法。

但我不需要向用户呈现任何页面或响应。

如何防止Rails控制台中的错误异常?

Completed 500 Internal Server Error in 10879ms

ActionView::MissingTemplate (Missing template

我的控制器

  def add_testing_record
    # p request.remote_ip
    # p params
    # ap params.class
    records = params["testing_record"].to_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
    records[:ip] = request.remote_ip
    binding.pry

    TestingCounter.create(records)
    respond_to do |format|

    end

  end

4 个答案:

答案 0 :(得分:2)

render nothing: truehead { 200 }都会删除错误,但它们也会导致浏览器显示空白页面。

如果您想留在同一页面上,您有两种选择:

  1. 在操作结束时呈现相同的视图。
  2. 通过ajax发送请求并返回head
  3. 第二,您的视图应包含以下内容:

    <%= link_to "do_stuff", foobar_path, remote: true %>
    

    而且,在你的控制器中:

    def foobar
      # process the request
      respond_to do |format|
        format.html {
          flash.now[:success] = "all ok"
          render "the/same/view/template/the/user/is/currently/seeing"
        }
        format.js {
          head 200
        }
      end
    end
    

    然而,在GET上创建资源很糟糕。你应该真的使用POST:

    <%= link_to "do_stuff", foobar_path, remote: true, method: :post %>
    

答案 1 :(得分:2)

如果您不想呈现页面

然后你可以使用

  respond_to do |format|
      render nothing: true
  end

答案 2 :(得分:1)

我更喜欢使用

head :ok

这样它只会返回带有标题的响应。

答案 3 :(得分:1)

head在后来的rails版本中更受欢迎

head :ok, :content_type => 'text/html'

http://guides.rubyonrails.org/layouts_and_rendering.html#using-head-to-build-header-only-responses