Sinatra active_record 的校验错误的展示

nickelchen · 2013年07月27日 · 最后由 nickelchen 回复于 2013年07月30日 · 2799 次阅读

请问下,如何在 Sinatra 中展示 ActiveRecord 的校验错误信息啊,比如 User.rb 中的

validates :name, :presence => true, :length => {:minimum => 4},

当用户注册时,name 字符少于 4 个,提示错误。 把 user 当做 locals 传给 view,同时在注册的 form 上面写如下代码是可以的。

- if (user ||= nil) && user.errors
  %p
    = user.errors.messages

但我不希望每个 model 都这样去 view 里写,况且如果有多个 model 的情景,就更不好搞了。 有没有跟 rails 那样的,models 的校验错误统一在 flash 里面,在 layout 里面就直接取出来一起展示? 你们在项目里是怎么处理的?谢谢!

🆙 Up.. Any help?

Rails 的校验错误也得自己写的

Rails 中的校验错误不是统一放在一个 flash 的 map 中么?然后可以统一迭代出来。

#3 楼 @nickelchen

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

你说的是这个吗……

@messiahxu 不需要一个个 model 的去写错误的。 在 layout 中

.container
      .row
        .span9
          = bootstrap_flash
          = yield

在 helper 中

def bootstrap_flash
    flash_messages = []
    flash.each do |type, message|
      # Skip empty messages, e.g. for devise messages set to nothing in a locale file.
      next if message.blank?

      type = :success if type == :notice
      type = :error   if type == :alert
      next unless ALERT_TYPES.include?(type)

      Array(message).each do |msg|
        text = content_tag(:div,
                           content_tag(:button, raw("&times;"), :class => "close", "data-dismiss" => "alert") +
                           msg.html_safe, :class => "alert fade in alert-#{type}")
        flash_messages << text if msg
      end
    end
    flash_messages.join("\n").html_safe
  end

@messiahxu 是我搞混了 flash 和 errors。。写了篇 blog 分析了下。http://www.nickelchen.com/2013/07/30/how-to-show-flash-messages

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