How do I display Ruby on Rails form validation error messages one at a time?

前端 未结 4 549
梦谈多话
梦谈多话 2020-12-02 14:12

I\'m trying to understand how I can achieve this. Can anyone advise me or point me in the right direction?

What I currently do, which is shown in the code snippet be

4条回答
  •  余生分开走
    2020-12-02 15:10

    ActiveRecord stores validation errors in an array called errors. If you have a User model then you would access the validation errors in a given instance like so:

    @user = User.create[params[:user]] # create will automatically call validators
    
    if @user.errors.any? # If there are errors, do something
    
      # You can iterate through all messages by attribute type and validation message
      # This will be something like:
      # attribute = 'name'
      # message = 'cannot be left blank'
      @user.errors.each do |attribute, message|
        # do stuff for each error
      end
    
      # Or if you prefer, you can get the full message in single string, like so:
      # message = 'Name cannot be left blank'
      @users.errors.full_messages.each do |message|
        # do stuff for each error
      end
    
      # To get all errors associated with a single attribute, do the following:
      if @user.errors.include?(:name)
        name_errors = @user.errors[:name]
    
        if name_errors.kind_of?(Array)
          name_errors.each do |error|
            # do stuff for each error on the name attribute
          end
        else
          error = name_errors
          # do stuff for the one error on the name attribute.
        end
      end
    end
    

    Of course you can also do any of this in the views instead of the controller, should you want to just display the first error to the user or something.

提交回复
热议问题