ruby on rails - respond_with return 200 instead of 422 -
ruby on rails - respond_with return 200 instead of 422 -
i have model active model validations using determine validity of search terms... if phone call controller endpoint invalid search, rails' respond_with returning 200 instead of 422.
if binding.pry within controller action, see: search_result.valid? => false
search_result.errors.full_messages => "last name must @ to the lowest degree 2 characters"
... why getting 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 blank') else attrs.each |key, value| errors.add(key, 'must @ to the lowest degree 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
when responding json, rails defaults 200. can specify result in controller using if/else statement:
if product.save render json: product, status: 201, location: product else render json: product.errors, status: 422 end
ruby-on-rails
Comments
Post a Comment