Ruby on Rails: how to get error messages from a child resource displayed?

Posted by randombits on Stack Overflow See other posts from Stack Overflow or by randombits
Published on 2010-04-21T02:57:52Z Indexed on 2010/04/21 3:03 UTC
Read the original article Hit count: 355

Filed under:
|
|

I'm having a difficult time understanding how to get Rails to show explicitly the error messages that a child resource is failing on when I render an XML template. Hypothetically, I have the following classes:

class School < ActiveRecord::Base
    has_many :students
    validates_associated :students
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

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
      @student = school.students.build
      @student.email = "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

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>

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby