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

后端 未结 8 1411
谎友^
谎友^ 2020-12-12 16:58

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.

8条回答
  •  孤城傲影
    2020-12-12 17:36

    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)
    

    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}"
    

提交回复
热议问题