如何从rails控制器重构渲染

时间:2015-05-17 01:21:44

标签: ruby-on-rails controller refactoring render

  def create
    render json: '{"error": "400"}', status: :bad_request and return if post_params[:post].blank?
    ...and more general create code....       
  end


  def update
    render json: '{"error": "400"}', status: :bad_request and return if post_params[:post].blank? 
     ...and more general update code.... 
  end

如何从创建和更新操作中重构上面的渲染错误400行,以便我不重复自己?

此验证将在我的代码中使用,我只想将其包含在我的操作中。

当我创建一个方法时,例如:

  def validations
    render json: '{"error": "400"}', status: :bad_request and return if post_params[:post].blank?       
end

我看到一个错误:

AbstractController::DoubleRenderError (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".):
  app/controllers/posts_controller.rb:43:in `create'

...当代码简单地按上面编写时不存在。

1 个答案:

答案 0 :(得分:0)

返回的json密钥对于状态是多余的,并且没有多大意义。使用返回一致键的东西,并可能在返回字符串中放入一些更有用的信息。

def create
  if post_params[:post].blank?
    render json: '{"status": "400"}', status: :bad_request
  else 
    .. do general create things
    render json: '{"non-error?": "200"}', status: 200
  end      
end


def update
  # basically the same as above 
end