【问题标题】:How to refactor render from rails controller如何从 Rails 控制器重构渲染
【发布时间】:2015-05-17 01:21:43
【问题描述】:
  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'

...当代码按上述方式简单编写时不存在。

【问题讨论】:

    标签: ruby-on-rails controller refactoring render


    【解决方案1】:

    返回的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2015-04-04
      • 2019-07-12
      • 2014-05-28
      • 1970-01-01
      • 2013-02-15
      相关资源
      最近更新 更多