我很难理解如何让Rails显示在呈现XML模板时验证失败的子资源的显式错误消息.假设我有以下课程:
class School < ActiveRecord::Base
has_many :students
validates_associated :students
def self.add_student(bad_email)
s = Student.new(bad_email)
students << s
end
end
class Student < ActiveRecord::Base
belongs_to :school
validates_format_of :email,
:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
:message => "You must supply a valid email"
end
现在,在控制器中,让我们假设我们想要构建一个简单的API,允许我们添加一个新的学校,其中有一个学生(我说,这是一个很糟糕的例子,但在问题中起到了作用)
class SchoolsController < ApplicationController
def create
@school = School.new
@school.add_student(params[:bad_email])
respond_to do |format|
if @school.save
# some code
else
format.xml { render :xml => @school.errors, :status => :unprocessable_entity }
end
end
end
end
现在验证工作正常了,因为邮箱与学生类中validates_format_方法中设置的正则表达式不匹配,所以一切都会消失.然而,我得到的结果如下:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Students is invalid</error>
</errors>
我希望上面用validates_format_设置的更有意义的错误消息显示出来.意思是,我想说:
<error>You must supply a valid email</error>
我做了什么错事让它不出现?