Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails: how to get error messages from a child resource displayed?
    primarykey
    data
    text
    <p>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:</p> <pre><code>class School &lt; ActiveRecord::Base has_many :students validates_associated :students def self.add_student(bad_email) s = Student.new(bad_email) students &lt;&lt; s end end class Student &lt; ActiveRecord::Base belongs_to :school validates_format_of :email, :with =&gt; /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message =&gt; "You must supply a valid email" end </code></pre> <p>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)</p> <pre><code>class SchoolsController &lt; 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 =&gt; @school.errors, :status =&gt; :unprocessable_entity } end end end end </code></pre> <p>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:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;errors&gt; &lt;error&gt;Students is invalid&lt;/error&gt; &lt;/errors&gt; </code></pre> <p>I want the more meaningful error message that I set above with validates_format_of to show up. Meaning, I want it to say:</p> <pre><code> &lt;error&gt;You must supply a valid email&lt;/error&gt; </code></pre> <p>What am I doing wrong for that not to show up? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload