在控制器中重构多个渲染

时间:2015-08-04 12:34:43

标签: ruby-on-rails ruby-on-rails-4 controller refactoring jbuilder

在我的rails控制器中,我必须在@group获得before_action之后检查该群组不是系统

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

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

.....

1 个答案:

答案 0 :(得分:1)

您可以拥有父控制器:

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密钥是非常误导的,应该是一个数组。