Rails的validate验证的本地化

本文介绍如何在Rails应用中自定义model验证失败时显示的错误信息,并提供了一个自定义的error_messages_for方法作为示例,使得错误信息更加友好且易于理解。

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,而不是中英文混杂的东东

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值