respond_with返回200而不是422

时间:2014-10-31 03:14:28

标签: ruby-on-rails

我有一个带有活动模型验证的模型,我用它来确定搜索项的有效性......如果我用无效的搜索调用我的控制器端点,则可以使用rails' respond_with返回200而不是422。

如果我在控制器操作中绑定.pry,我看到: search_result.valid? =>假

search_result.errors.full_messages => "姓氏必须至少为2个字符"

...为什么我得到200?

model:

    class SearchResult
      include ActiveModel::Validations
      validate :ensure_terms_presence_and_length

      attr_reader :attrs

      def initialize(attrs = {})
        @attrs = attrs
      end

      def users
        valid? ? SearchClient.search(attrs) : []
      end

      private

      def ensure_terms_presence_and_length
        if attrs.values.join.blank?
          errors.add(:base, 'search fields cannot be blank')
        else
          attrs.each do |key, value|
            errors.add(key, 'must be at least 2 characters') if value.length < 2
          end
        end
      end
    end

 controller:

    module Api::V1
      class SearchUsersController < ApiController
        respond_to :json

        def index
          search_result = SearchResult.new(permitted_params)
          respond_with search_result, serializer: SearchResultSerializer
        end

        private

        def permitted_params
          params.permit(
            :username,
            :first_name,
            :last_name,
            :email
          )
        end
      end
    end

2 个答案:

答案 0 :(得分:0)

响应JSON时,Rails默认为200.您可以使用if / else语句在控制器中指定结果:

 if product.save
     render json: product, status: 201, location: product
   else
     render json: product.errors, status: 422
 end

答案 1 :(得分:0)

因此经过一些实验后我发现,只有创建/更新操作实际上会在出现错误时返回422状态---但是,您仍然需要手动调用.valid?为了使response_With返回无效的状态代码+序列化的错误对象。

如果你使用show或index动作,rails不关心有效吗?并将永远返回200。

相关问题