Ruby on Rails:如何从显示的子资源中获取错误消息? [英] Ruby on Rails: how to get error messages from a child resource displayed?
问题描述
我很难理解如何让 Rails 在呈现 XML 模板时为未通过验证的子资源显示显式错误消息.假设我有以下课程:
I'm having a difficult time understanding how to get Rails to show an explicit error message for a child resource that is failing validation when I render an XML template. Hypothetically, I have the following classes:
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 以允许我们添加一个包含学生的新学校(我再说一遍,这是一个糟糕的例子,但它的作用是为了问题)
Now, in the controller, let's say we want to build a trivial API to allow us to add a new School with a student in it (again, I said, it's a terrible example, but plays its role for the purpose of the question)
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
现在验证工作得很好,事情失败了,因为电子邮件与 Student 类中 validates_format_of 方法中设置的正则表达式不匹配.但是我得到的输出如下:
Now the validation is working just fine, things die because the email doesn't match the regex that's set in the validates_format_of method in the Student class. However the output I get is the following:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Students is invalid</error>
</errors>
我希望显示我在上面使用 validates_format_of 设置的更有意义的错误消息.意思是,我想说:
I want the more meaningful error message that I set above with validates_format_of to show up. Meaning, I want it to say:
<error>You must supply a valid email</error>
我做错了什么才没有出现?
What am I doing wrong for that not to show up?
推荐答案
在 School
模型中添加验证块以合并错误:
Add a validation block in the School
model to merge the errors:
class School < ActiveRecord::Base
has_many :students
validate do |school|
school.students.each do |student|
next if student.valid?
student.errors.full_messages.each do |msg|
# you can customize the error message here:
errors.add_to_base("Student Error: #{msg}")
end
end
end
end
现在 @school.errors
将包含正确的错误:
Now @school.errors
will contain the correct errors:
format.xml { render :xml => @school.errors, :status => :unprocessable_entity }
注意:
您不需要单独的方法来将新学生添加到学校,请使用以下语法:
You don't need a separate method for adding a new student to school, use the following syntax:
school.students.build(:email => email)
Rails 3.0+ 更新
errors.add_to_base
已从 Rails 3.0 及更高版本中删除,应替换为:
Update for Rails 3.0+
errors.add_to_base
has been dropped from Rails 3.0 and above and should be replaced with:
errors[:base] << "Student Error: #{msg}"
这篇关于Ruby on Rails:如何从显示的子资源中获取错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!