搜尋

首頁  >  問答  >  主體

ruby - rails的表單驗證後格式錯亂問題

舉個例子,在表單中有這樣的內容:

    <dl>                                                                                                                                                                                                                                                                        
      <dt>
        <%= f.label :subject %>
      </dt>
      <dd>
        <%= f.text_field :subject %>
      </dd>
    </dl>

在瀏覽器中顯示成:

■Subject

(※注:■由CSS生成)

如果對表單進行驗證,驗證後再顯示的格式就亂了,變成這樣:

■
Subject

為什麼會錯位呢?

天蓬老师天蓬老师2851 天前774

全部回覆(1)我來回復

  • 天蓬老师

    天蓬老师2017-04-21 11:17:23

    You should override ActionView::Base.field_error_proc. It's currently defined as this within ActionView::Base:

     @@field_error_proc = Proc.new{ |html_tag, instance| 
       "<p class=\"field_with_errors\">#{html_tag}</p>".html_safe
     }
    

    You can override it by putting this in your application's class inside config/application.rb:

    config.action_view.field_error_proc = Proc.new { |html_tag, instance| 
      "#{html_tag}".html_safe 
    }
    

    Restart rails server for this change to take effect.

    (全文抄襲自 http://stackoverflow.com/questions/5267998/rails-3-field-with-errors-wrapper-changes-the-page-appearance-how-to-avoid-t)


    當然,更推薦改成這樣

    config.action_view.field_error_proc = Proc.new do |html_tag, instance|
      class_attr_index = html_tag.index 'class='
    
      if class_attr_index
        html_tag.insert class_attr_index+7, 'error '
      else
        html_tag.insert html_tag.index('>'), ' class="error"'
      end
    end
    

    回覆
    0
  • 取消回覆