【问题标题】:Refactoring multiple render in controller在控制器中重构多个渲染
【发布时间】:2015-08-04 12:34:43
【问题描述】:

在我的 rails 控制器中,我必须在获得 @groupbefore_action 后检查该组不是 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

.....

【问题讨论】:

  • 请加callback('before_action')部分,不是很清楚你在做什么。
  • 我确认您应该添加您使用的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"
  • my before_action only find do begin @group = current_store.groups.find(params[:group_id]) rescue ActiveRecord::RecordNotFound render_404 return end

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


【解决方案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 键非常具有误导性,应该是一个数组。

【讨论】:

  • 感谢您的回答。会试试的。
  • 像魅力一样工作。感谢您提供错误提示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 2013-01-27
相关资源
最近更新 更多