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

后端 未结 8 1298
谎友^
谎友^ 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:55

    This is not a public API yet, but Rails 5 stable seems to have ActiveModel::Errors#copy! to merge errors between two models.

    user  = User.new(name: "foo", email: nil)
    other = User.new(name: nil, email:"foo@bar.com")
    
    user.errors.copy!(other.errors)
    user.full_messages #=> [ "name is blank", "email is blank" ] 
    

    Again, this is not officially published yet (I accidentally find this one before monkey-patching Errors class), and I'm not sure it will be.

    So it's up to you.

    0 讨论(0)
  • 2020-12-12 18:01

    You should use following in the rhtml.

    <%= error_messages_for :school, :student %>
    

    To skip "Students is invalid" message use following in the student.rb

      def after_validation
        # Skip errors that won't be useful to the end user
        filtered_errors = self.errors.reject{ |err| %w{ student}.include?(err.first) }
        self.errors.clear
        filtered_errors.each { |err| self.errors.add(*err) }
      end
    

    EDITED

    Sorry after_validation must be in a school.rb
    
    0 讨论(0)
提交回复
热议问题