Rails: Getting rid of generic “X is invalid” validation errors

前端 未结 2 1925
南方客
南方客 2021-01-02 11:48

I have a sign-up form that has nested associations/attributes whatever you want to call them.

My Hierarchy is this:

class User < ActiveRecord::Bas         


        
相关标签:
2条回答
  • 2021-01-02 12:12

    Use after_validation method

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

    EDITED

    Note:-

    Add the in the following list in your case it's User or user. you can add multiple if you have multiple assosciation separated by space.

    %w{ User user }.include?(err.first) #### This piece of code from the above method has logic which reject the errors which won't be useful to the end user
    
    0 讨论(0)
  • 2021-01-02 12:16

    Salil's answer was almost right but he never made it 100%. Here is the correct way to do it:

    def after_validation
        # Skip errors that won't be useful to the end user
        filtered_errors = self.errors.reject{ |err| %{ person }.include?(err.first) }
    
        # recollect the field names and retitlize them
        # this was I won't be getting 'user.person.first_name' and instead I'll get
        # 'First name'
        filtered_errors.collect{ |err|
          if err[0] =~ /(.+\.)?(.+)$/
            err[0] = $2.titleize
          end
          err
        }
    
        # reset the errors collection and repopulate it with the filtered errors.
        self.errors.clear
        filtered_errors.each { |err| self.errors.add(*err) }
      end
    
    0 讨论(0)
提交回复
热议问题