Rails 关于 Rails validate 提示的 HTML 代码

colorfulberry · 2014年10月11日 · 最后由 colorfulberry 回复于 2014年10月11日 · 2226 次阅读

rails 中可以用这种方式来捕获验证异常

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-error">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li>* <%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

需要在对应的页面用 render

有没有插件来做这个代码的事情? @Rei@kepaning

Simple Form was designed to be customized as you need to. Basically it's a stack of components that are invoked to create a complete html input for you, which by default contains label, hints, errors and the input itself. It does not aim to create a lot of different logic from the default Rails form helpers, as they do a great job by themselves.

搬运自 https://github.com/plataformatec/simple_form

我最后在 config 的 initail 中加入新的文件

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|

    %{<span class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></span>}.html_safe

end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号