복붙노트

[RUBY-ON-RAILS] 한 번에 레일 양식 유효성 검사 오류 메시지 하나에 루비를 표시하는 방법

RUBY-ON-RAILS

한 번에 레일 양식 유효성 검사 오류 메시지 하나에 루비를 표시하는 방법

나는 이것을 달성 할 수있는 방법을 이해하기 위해 노력하고있어. 할 수있는 모든 사용자의 올바른 방향으로 조언 날 또는 포인트 나?

이것은 한 번에 표시하는 각 필드에서 1 에러를 허용한다. 그것은 내가 원하는하지만 아주 정확하게 거의이다. 나는 한 번에 한 전체 오류 메시지를 표시합니다. 예를 들면 이름은 비워 둘 수 없습니다. 그 해결되면 그 다음 오류로 이동합니다. 사용자가 자신의 마지막 이름에 숫자를 추가 그래서 경우 그 오류가 수정되었습니다 때 마지막 이름 오류로 이동하거나 아니면 이메일을 보내 것 등이 허용되었다 그것은 더 이상 비워 둘 수 없습니다 것입니다하지만 그것은 단지 문자를 알리는 다른 오류를 표시 할 사용자 필드 경우 자신의 성 밖으로 올바르게.

<% @user.errors.each do |attr, msg| %>
<%= "#{attr} #{msg}" if @user.errors[attr].first == msg %> 
<% end %>

해결법

  1. ==============================

    1.액티브 매장 배열라는 오류 오류를 확인 중. 당신이 사용자 모델을 가지고 있다면 당신은 너무 같은 지정된 인스턴스의 유효성 검사 오류에 액세스합니다 :

    액티브 매장 배열라는 오류 오류를 확인 중. 당신이 사용자 모델을 가지고 있다면 당신은 너무 같은 지정된 인스턴스의 유효성 검사 오류에 액세스합니다 :

    @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
    

    물론 당신이 대신 컨트롤러의 뷰에서이 작업을 수행 할 수 있습니다, 당신은 단지 사용자 또는 뭔가를 첫 번째 오류를 표시하고자한다.

  2. ==============================

    2.몇 시간 동안 실험 후에 나는 그것을 알아 냈다.

    몇 시간 동안 실험 후에 나는 그것을 알아 냈다.

    <% if @user.errors.full_messages.any? %>
      <% @user.errors.full_messages.each do |error_message| %>
        <%= error_message if @user.errors.full_messages.first == error_message %> <br />
      <% end %>
    <% end %>
    

    더 나은 :

    <%= @user.errors.full_messages.first if @user.errors.any? %>
    
  3. ==============================

    3.더 좋은 아이디어,

    더 좋은 아이디어,

    그냥 텍스트 필드 아래에 오류 메시지를 넣어하려는 경우, 당신은 다음과 같이 할 수있다

    .row.spacer20top
      .col-sm-6.form-group
        = f.label :first_name, "*Your First Name:"
        = f.text_field :first_name, :required => true, class: "form-control"
        = f.error_message_for(:first_name)
    

    error_messages_for은 무엇인가? -> 음,이 멋진 물건을 할 수있는 아름다운 해킹입니다

    # Author Shiva Bhusal
    # Aug 2016
    # in config/initializers/modify_rails_form_builder.rb
    # This will add a new method in the `f` object available in Rails forms
    class ActionView::Helpers::FormBuilder
      def error_message_for(field_name)
        if self.object.errors[field_name].present?
          model_name              = self.object.class.name.downcase
          id_of_element           = "error_#{model_name}_#{field_name}"
          target_elem_id          = "#{model_name}_#{field_name}"
          class_name              = 'signup-error alert alert-danger'
          error_declaration_class = 'has-signup-error'
    
          "<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
          "#{self.object.errors[field_name].join(', ')}"\
          "</div>"\
          "<!-- Later JavaScript to add class to the parent element -->"\
          "<script>"\
              "document.onreadystatechange = function(){"\
                "$('##{id_of_element}').parent()"\
                ".addClass('#{error_declaration_class}');"\
              "}"\
          "</script>".html_safe
        end
      rescue
        nil
      end
    end
    

    결과

    오류가 발생한 후 생성 된 마크 업

    <div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
    <script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>
    

    해당 SCSS

      .has-signup-error{
        .signup-error{
          background: transparent;
          color: $brand-danger;
          border: none;
        }
    
        input, select{
          background-color: $bg-danger;
          border-color: $brand-danger;
          color: $gray-base;
          font-weight: 500;
        }
    
        &.checkbox{
          label{
            &:before{
              background-color: $bg-danger;
              border-color: $brand-danger;
            }
          }
        }
    
  4. ==============================

    4.나는 이런 식으로 해결 :

    나는 이런 식으로 해결 :

    <% @user.errors.each do |attr, msg| %>
      <li>
        <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
      </li>
    <% end %>
    

    이 방법은 오류 메시지에 대한 로케일을 사용하고 있습니다.

  5. from https://stackoverflow.com/questions/7878662/how-to-display-ruby-on-rails-form-validation-error-messages-one-at-a-time by cc-by-sa and MIT license