在控制器中重构多重渲染

Refactoring multiple render in controller

在我的 rails 控制器中,我必须在使用 before_action 获得 @group 后检查该组不是 system.

但我的控制器中有很多重复项。我试图变成一个单独的方法,但我得到了经典的方法:

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

这是我的代码的一部分,没有给我错误的单独方法。

def destroy
  if @group.is_system?
    render json: { errors: 'You can\'t delete a group system' }, status: 403
    return
  end

  ...
end

def update
  if params[:group] && !params[:group].empty?
    if @group.is_system?
      render json: { errors: 'You can\'t edit a group system' }, status: 403
      return
    end

    ...

  else
    render json: { errors: 'Missing correct parameters' }, status: :unprocessable_entity
  end
end

.....

您可以在父控制器中拥有:

def render_errors(errors, status)
  render json: { errors: Array(errors) }, status: status
end

def render_403(errors)
  render_errors(errors, 403)
end

def render_422(errors)
  render_errors(errors, 422)
end

那么在你的行动中:

before_action :check_system

def check_system      
  # I assume you already defined @group
  render_403('You can\'t delete a group system') if @group.is_system?
end

请注意,我更改了您的一些代码:errors 键只是一个字符串是非常误导的,应该是一个数组。