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

后端 未结 8 1393
谎友^
谎友^ 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条回答
  •  Happy的楠姐
    2020-12-12 17:49

    Update Rails 5.0.1

    You can use Active Record Autosave Association

    class School < ActiveRecord::Base
        has_many :students, autosave: true
        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
    
    @school = School.new
    @school.build_student(email: 'xyz')
    @school.save
    @school.errors.full_messages ==> ['You must supply a valid email']
    

    reference: http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

提交回复
热议问题