代码之家  ›  专栏  ›  技术社区  ›  AnApprentice

如何更新Rails控制器以在建模时返回错误。是否创建错误?

  •  3
  • AnApprentice  · 技术社区  · 7 年前

    我有以下控制器:

    class Api::V1::FeedbacksController < ApplicationController
    
      before_action :authenticate_user!
    
      def create
    
        @feedback = current_user.feedbacks.create(
          feedback_type: params[:selectedType],
          message: params[:message]
        )
    
        json_response(@feedback)
      end
    
    private
    
      def json_response(object, status = :ok)
        render json: object, status: status
      end
    
    end
    

    验证:消息,存在:true,长度:{in:1..1000}

    如果上述创建方法失败,Rails 5中让控制器返回错误的正确方法是什么?

    1 回复  |  直到 5 年前
        1
  •  3
  •   MrYoshiji    7 年前

    通常的rails方法是测试 .save :

    def create
      @feedback = current_user.feedbacks.new(
        feedback_type: params[:selectedType],
        message: params[:message]
      )
      if @feedback.save
        json_response(@feedback)
      else
        json_response(@feedback.errors, :some_other_status)
        # you could also send @feedback directly and then in your JSON response handler
        # to test if the json contains values in the object.errors array
      end
    end
    
    private
    
    def json_response(object, status = :ok)
      render json: object, status: status
    end
    

    您可以使用此文档查找要返回的正确代码 https://cloud.google.com/storage/docs/json_api/v1/status-codes