`
liuqiang
  • 浏览: 158336 次
  • 性别: Icon_minigender_1
  • 来自: 华东
社区版块
存档分类
最新评论

Rails的validate验证的本地化

阅读更多

rails在model层进行验证,在页面直接调用

<%= error_messages_for 'model名' %>

可这样页面出来的错误信息全部是英文的,而且rails是直接取数据库的字段名来显示错误信息,这样肯定是不合理的.我们通过自定义一个 error_messages_for 方法作为helper,显示在model验证时自定义的:message

module ApplicationHelper
 def error_messages_for(object_name, options = {})
  options = options.symbolize_keys
  object = instance_variable_get("@#{object_name}")
  if object
  unless object.errors.empty?

  error_lis = []
  object.errors.each{ |key,msg| error_lis << content_tag("li", msg) }

  content_tag("div",
  content_tag(
  options[:header_tag] || "h2",
                " 发生#{object.errors.count}个错误"
            ) +content_tag("ul", error_lis),"id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
              )
  end
 end
 end
end

以后,我们在model层这样写:

 validates_presence_of(:name, :message => "请给你的blog取个好名字!")

当发生name为空时将显示你定义的message,而不是中英文混杂的东东

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics