Rails 6.1.4 弃用警告:使用“.”渲染操作

B-M*_*B-M 21 ruby-on-rails ruby-on-rails-6.1

我在运行时收到弃用警告rails test。该警告如下。任何有助于确定我做错了什么的帮助都会受到赞赏。

(编辑:旁注,渲染必须中断并从当前控制器调用返回。我尝试使用ApplicationController.render(...)代替当前调用render,但没有从控制器调用返回,并且我收到了错误/警告:no_content rendered。)

警告:

DEPRECATION WARNING: Rendering actions with '.' in the name is deprecated: actions/action_success.json (called from update at /<path>/app/controllers/table_base_controller.rb:39)
Run Code Online (Sandbox Code Playgroud)

render抛出警告的代码具体是在控制器中调用:

render('/actions/action_success.json', locals: {
  view: action.lookup_view('default'),
  action: action,
  area: current_area,
  account: current_account
}) 
Run Code Online (Sandbox Code Playgroud)

我已经尝试按照指示取消.json(也尝试添加template: <path>、尝试file: <path>),但是,我在测试控制台中收到此错误:

Error:
TableControllerTest#test_Admin_should_update_via_loan_table:
ActionView::MissingTemplate: Missing template actions/action_success with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}. Searched in:
  * "/<path>/app/views"

    app/controllers/table_base_controller.rb:39:in `update'
    app/controllers/application_controller.rb:79:in `with_account'
    test/controllers/table_controller_test.rb:14:in `block in <class:TableControllerTest>'
Run Code Online (Sandbox Code Playgroud)

有问题的文件(路径app/views/actions/action_success.json.jbuilder:):

# frozen_string_literal: true

json.status 'success'
json.status_code 200
json.messages action.messages

if view
  json.result do
    json.partial! view.to_s, result: action.result, locals: { area: area }
  end
else
  json.result action.result
end
Run Code Online (Sandbox Code Playgroud)

小智 25

弃用包含 a 的部分名称.是为了防止解析部分名称时出现歧义。我们应该明确声明格式,而不是将它们包含在我们传递给渲染的部分名称中。

如果您传入的字符串中没有格式,您需要确保formats渲染预期包含您正在使用的格式,在本例中json,这不是默认格式之一。

您可以将其作为选项发送(并使部分名称也成为选项),如下所示:

render(
  partial: '/actions/action_success',
  formats: [:json],
  locals: {
    view: action.lookup_view('default'),
    action: action,
    area: current_area,
    account: current_account
  }
) 
Run Code Online (Sandbox Code Playgroud)