我正在做一个旧的Rails 2项目,
在我的模型课中,我有一个验证:
class Student < ActiveRecord::Base
validates_uniqueness_of :foo, :scope => [:type, :gender], :message => "Already have such student"
...
end
它基于foo
和type
属性检查字段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
答案 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
实际上,即使学生无效,也永远不会为零。因此您的代码将始终呈现正常状态