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.
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
Now @school.errors will contain the correct errors:
format.xml { render :xml => @school.errors, :status => :unprocessable_entity }
Note:
You don't need a separate method for adding a new student to school, use the following syntax:
school.students.build(:email => email)
errors.add_to_base has been dropped from Rails 3.0 and above and should be replaced with:
errors[:base] << "Student Error: #{msg}"