论坛首页 编程语言技术论坛

RecordActive中default_errors_messages的改变

浏览 1718 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-03-15   最后修改:2009-03-15
正在看railsspace_building_a_social_networking_website_with_ruby_on_rails一书,Rails_Space的测试代码,在测试时发现用下列验证输入信息过长的错误。在Rails2.2.2中发生错误。
error_messages = ActiveRecord::Errors.default_error_messages
sprintf(error_messages[:too_long], length)
经查看代码,在rails-2.0前,可以把default_error_messages中%d替换成数字。
在Rails2.2.2中,default_error_messages定义发生了变化,不能把{{counter}}提换成数字。可以在script/console 中,通过输入ActiveRecord::Errors.default_error_messages查看详细内容。
2.0以前,在validations.rb中
   @@default_error_messages = {
      :inclusion => "is not included in the list",
      :exclusion => "is reserved",
      :invalid => "is invalid",
      :confirmation => "doesn't match confirmation",
      :accepted  => "must be accepted",
      :empty => "can't be empty",
      :blank => "can't be blank",
      :too_long => "is too long (maximum is %d characters)",
      :too_short => "is too short (minimum is %d characters)",
      :wrong_length => "is the wrong length (should be %d characters)",
      :taken => "has already been taken",
      :not_a_number => "is not a number",
      :greater_than => "must be greater than %d",
      :greater_than_or_equal_to => "must be greater than or equal to %d",
      :equal_to => "must be equal to %d",
      :less_than => "must be less than %d",
      :less_than_or_equal_to => "must be less than or equal to %d",
     dd => "must be odd",
      :even => "must be even"
    }
2.2.2,在validations.rb中
   def default_error_messages 
    ActiveSupport::Deprecation.warn("ActiveRecord::Errors.default_error_messages
      has been deprecated. Please use
      I18n.translate('activerecord.errors.messages').")
      I18n.translate 'activerecord.errors.messages'
    end
   发表时间:2009-04-17   最后修改:2009-04-17
zhao_j_long 写道

在Rails2.2.2中,default_error_messages定义发生了变化,不能把{{counter}}提换成数字。


google后看到解决方法,顺手贴下,因为自己之前也有疑问,而楼主并没有说解决方法..

correct_error_message = I18n.translate
"activerecord.errors.messages.too_long", :count=>max_length

因为rails2.2.2之后,error message要集中处理(多语言的问题),所以通过I18n.translate这个method来代入参数就好了,不需要自己手动修改error message.

0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics