不推荐使用":nothing"选项,将在Rails 5.1中删除

Lin*_*der 101 ruby-on-rails ruby-on-rails-5

这个代码在rails 5中

class PagesController < ApplicationController
  def action
    render nothing: true
  end
end
Run Code Online (Sandbox Code Playgroud)

导致以下弃用警告

DEPRECATION WARNING: :nothing` option is deprecated and will be removed in Rails 5.1. Use `head` method to respond with empty response body.
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

Lin*_*der 158

根据导轨源,这在通过nothing: true导轨5 时在引擎盖下完成.

if options.delete(:nothing)
  ActiveSupport::Deprecation.warn("`:nothing` option is deprecated and will be removed in Rails 5.1. Use `head` method to respond with empty response body.")
  options[:body] = nil
end
Run Code Online (Sandbox Code Playgroud)

只需更换nothing: truebody: nil因此应该解决的问题.

class PagesController < ApplicationController
  def action
    render body: nil
  end
end
Run Code Online (Sandbox Code Playgroud)

或者你可以使用 head :ok

class PagesController < ApplicationController
  def action
    head :ok
  end
end
Run Code Online (Sandbox Code Playgroud)

  • `head`方法是首选语法.更清洁. (16认同)
  • @FellowStranger,它不是`render head :: ok`,它是`head:ok`.没有`渲染`.我也在努力解决这个问题. (12认同)
  • 如果您想更改状态代码,除了`:ok`之外还有其他选项http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option (11认同)
  • `render body:nil`为我工作,`render head:ok`没有(它给出了一些双重渲染错误). (3认同)
  • 另一个例子是`head:unauthorized`返回状态码401 (2认同)