验证失败时呈现状态

时间:2019-07-26 07:25:38

标签: ruby-on-rails

我正在做一个旧的Rails 2项目,

在我的模型课中,我有一个验证:

class Student < ActiveRecord::Base
  validates_uniqueness_of :foo, :scope => [:type, :gender], :message => "Already have such student"
 ...
end

它基于footype属性检查字段gender的唯一性,如果在创建新学生时已经存在具有这些属性的student,则会出现错误消息提高。

我的问题是,通过此验证,我如何才能调用render :status => 422, :json=>"Already have such student"而不是该错误消息?有可能

====控制器====

class StudentsController < BaseController

  def create
       student = Student.new({...})

       # Since there are other validations in Student class, it could be any reason student is nil here.
       if student.nil?
          render :status => :unprocessable_entity, :json => "Failed to create student."
       else
          render :status => :ok, :json=> student.to_json
       end
  end 
end

1 个答案:

答案 0 :(得分:1)

尝试使用此代码

    class StudentsController < BaseController

      def create
        student = Student.new({...})

        if student.save
          render :status => :ok, :json=> student.to_json
        else
          render :status => :unprocessable_entity, :json => student.errors.full_messages
        end
      end 
    end

实际上,即使学生无效,也永远不会为零。因此您的代码将始终呈现正常状态